imagecreatefromstring no jpeg support in this php build

PHP imagecreatefromstring(): GD-jpeg, libjpeg: восстанавливаемая ошибка

Я пытаюсь загрузить изображение с внешнего сайта, над которым у меня нет контроля.

большую часть времени он работает нормально (сотни снимков пока тестируется).

теперь он дает мне эту ошибку для одного конкретного изображения:

imagecreatefromstring(): GD-jpeg, libjpeg: восстанавливаемая ошибка: поврежденные данные JPEG: преждевременное завершение сегмента данных

совет, который я читал до сих пор, предполагает добавление:

но это не имело никакого эффекта, и я все еще получаю ошибки. Я делаю ini_set непосредственно перед вызовом. Это важно?

Я действительно застрял на том, как игнорировать эту ошибку и продолжить.

4 ответов

проблема была связана с моей обработкой ошибок. Я бы настроил обработчик ошибок, поэтому мой вызов

не подавлял ошибки.

путем изменения моего обработчика ошибок с помощью:

теперь я могу правильно подавлять некоторые ошибки.

Это можно решить с:

если вы просто показываете изображение, то я предлагаю просто прочитать содержимое и отобразить изображение следующим образом:

если вы хотите скопировать изображение на свой сервер, у вас есть несколько вариантов, два из которых являются copy() функция или метод, используемый выше, а затем fwrite() :

Я надеюсь, что вы найдете использовать в выше

учитывая, что вы хотите сделать эскиз и сохранить его, вы можете реализовать удобную функцию изменения размера, такую как:

затем, после того, как вы скопировали файл на свой сервер, используя один из моих методов в моем ответе выше, вы можете просто применить функцию следующим образом:

эта функция служит мне очень хорошо. Я применить его к 1000 снимков в день и он работает как шарм.

Источник

imagecreatefromstring

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

imagecreatefromstring — Создание нового изображения из потока представленного строкой

Описание

Список параметров

Строка содержащая данные изображения.

Возвращаемые значения

Ошибки

imagecreatefromstring() вызывает ошибку уровня E_WARNING, если данные в неподдерживаемом формате.

Список изменений

ВерсияОписание
8.0.0В случае успешного выполнения функция теперь возвращает экземпляр GDImage ; ранее возвращался ресурс ( resource ).
7.3.0Добавлена поддержка WEBP (если поддерживается используемой libgd).

Примеры

Пример #1 Пример использования imagecreatefromstring()

Результатом выполнения данного примера будет что-то подобное:

imagecreatefromstring no jpeg support in this php build. Смотреть фото imagecreatefromstring no jpeg support in this php build. Смотреть картинку imagecreatefromstring no jpeg support in this php build. Картинка про imagecreatefromstring no jpeg support in this php build. Фото imagecreatefromstring no jpeg support in this php build

Смотрите также

User Contributed Notes 17 notes

While downloading images from internet, it’s easiest to let php decide what is the file type. So, forget using imagecreatefromjpg, imagecreatefromgif and imagecreatefrompng. Instead, this is the way to go:

My site allows anonymous uploads to a web-accessible location (that will execute a script if it finds one).

Naturally, I need to verify that only harmless content is accepted. I am expecting only images, so I use:

So you guys don’t spend an hour trying to figure out why your script keeps running out of memory when you’re using this or the other imagecreatefrom functions. GD uncompresses the image when you use these functions, and this can lead to your script running out of memory.

If you download a rawimage save it on your computer to jpeg so the file size comes down, GD will automatically convert it to the raw and you can possibly run out of memory.

[Editor’s note: BMP will be supported as of PHP 7.2.0.]

In case it’s not obvious from the lack of «imagecreatefrombmp()» in GD, this function cannot handle plain old BMP files either.

I know a lot of people have been having trouble using images from the Sprint PPC6700 with GD. The jpeg library always thows an error about 16 bytes of extraneous data. I decided to poke around in a hex editor and found those extraneous bytes occur right at the end of the exif data.

By removing this extraneous data, images can easily be manipulated by GD and the EXIF extension as a normal images. This also removes any problems using the images with GIMP which must rely on the same jpeg libraries.

Here is a function that will check to see if an image is from the PPC6700 and then remove the extraneous data for you. The result can successully be used with imagecreatefromstring

Author: Paul Visco
IM: paulsidekick
Created: 2-12-06

//get the file contents
$data = file_get_contents($orig);

I use dynamically generated images that require a little touch-up before being displayed. So essentially I do some base work, then store the images in a memory cache (APC), reload the images again from the cache later on «into» GD, do final processing and then display the image.
Since I wanted to avoid a lot of disc access I used the output buffering functions:

// Do your image processing stuff

// Put stuff into cache

// Do final editing stuff and output image
?>

Of course this is a condensed example but I just wanted to share the idea.

An easy example to help understanding this function.

The function will try to auto-determine file format (jpg, gif, png. ), and will return false if fails.

Create an image resource from file, without knowing image type:

A note to the previous question (if you still don’t know it :)).

GIF’s are 256 colors (or 8 bit), and the resample function needs true color I guess. that’s why it works with JPG’s and not with GIF’s.

Next thing. you take a string, write it to file, open the file (imagecreatefromgif), and delete the file again.

if you do imagecreatefromstring($string) you can skip the temporary file part.

If you let them, the PHP function will return an error «Data is not in a recognized format in».

If you have this situation :

$image_string=str_replace(«data:image/png;base64,»,»»,$image_string);
$image_string = base64_decode($image_string);
$img = imagecreatefromstring($image_string);

I run a blogging site that allowed users to publish images from their cell phones. For some reason, the nokia 3220 produces jpegs with extrandeous data before the EOF 0xFFF9

I wrote this class to allow you to fix the images so that they can be used with GD to resize and manipulate. Without applying the fix both GD and gimp report errors for the file. If basically keeps eating bytes from the junk part till the file is a valid jpeg. Here is an example bunk pic written by a nokia 3220 that you cna test it with http://www.shawnrider.com/moblog/cache/0854747001121624103.jpg

/*
Author: Paul Visco
Hompage: http://www.elmwoodstrip.com?u=paul
AIM: paulsidekick
Notes: The file allows you fix the jpegs created by the Nokia 3220 picture phone so that they can be manipulated using the GD library with PHP.

Usage: Simply instanitiate the class and then call the fix method for each image.
e.g.
$nokia = new nokia;
$nokia->debug =»y»;
$nokia->fix(«yourpic.jpg»);
*/

//load the file into a string
$this->str = file_get_contents($this->file);

//test to see if it is a nokia image or if it has been corrupted previously
if (substr_count($this->str, chr(0x28).chr(0x36).chr(0x28).chr(0x2B)) == 0 || @imagecreatefromstring($this->str))
<
if ($this->debug ==»y»)
<
echo «\n
«.$this->file.» is not a corrupted Nokia pic»;
>

//strip out the funk e crap from the file
$this->eat($this->str);

//return true for fixed
return true;

//check the image
$this->img = @imagecreatefromstring($this->str);

//check the image again
$this->img = @imagecreatefromstring($this->str);
>

if ($this->debug ==»y»)
<
//notify the user it’s fixed
echo «\n
Nasty bits eaten!! «.$this->file.» is fixed now thanks to p:labs!»;
>
return true;
>

The only way I managed to resolve the loading of image files from file data either on local site or from off-site protocols is as follows. I hope this saves someone else the two hours of debugging and looking for good examples.
[PHP]

Here is the code I did to create a thumbnail image from the database blob field. The trick is to use «imagecreatefromstring()» to create an image file.

Источник

imagecreatefromjpeg

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecreatefromjpeg — Создаёт новое изображение из файла или URL

Описание

imagecreatefromjpeg() возвращает идентификатор изображения, представляющего изображение полученное из файла с заданным именем.

Список параметров

Путь к JPEG картинке.

Возвращаемые значения

Возвращает объект изображения в случае успешного выполнения или false в случае возникновения ошибки.

Список изменений

ВерсияОписание
8.0.0В случае успешного выполнения функция теперь возвращает экземпляр GDImage ; ранее возвращался ресурс ( resource ).

Примеры

Пример #1 Пример обработки ошибки при загрузке JPEG

header ( ‘Content-Type: image/jpeg’ );

$img = LoadJpeg ( ‘bogus.image’ );

Результатом выполнения данного примера будет что-то подобное:

imagecreatefromstring no jpeg support in this php build. Смотреть фото imagecreatefromstring no jpeg support in this php build. Смотреть картинку imagecreatefromstring no jpeg support in this php build. Картинка про imagecreatefromstring no jpeg support in this php build. Фото imagecreatefromstring no jpeg support in this php build

User Contributed Notes 34 notes

This function does not honour EXIF orientation data. Pictures that are rotated using EXIF, will show up in the original orientation after being handled by imagecreatefromjpeg(). Below is a function to create an image from JPEG while honouring EXIF orientation data.

This little function allows you to create an image based on the popular image types without worrying about what it is:

If imagecreatefromjpeg() fails with «PHP Fatal error: Call to undefined function: imagecreatefromjpeg()», it does NOT necessarily mean that you don’t have GD installed.

Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: ‘image.jpg’ is not a valid JPEG file

This only happens with certain images, which when opened in any program are ok, it even uploads to the version of the site I have on localhost with no problems,

To fix try below code snippet-

In John’s human readable code version of Karolis code to dynimicly allocate need memory there are a few bugs. If you didn’t compile with the «—enable-memory-limit» option, this script will error with a level E_ERROR. Bellow is a fixed version rapped as a function. To view replacement functions for memory_get_usage() look at http://us2.php.net/manual/en/function.memory-get-usage.php

did you found that sometimes it hang the php when imagecreatefromjpeg() run on bad JPEG. I found that this is cause by the JPEG file U used dont have EOI (end of image)
the FF D9 at the end of your JPEG

JPEG image should start with 0xFFD8 and end with 0xFFD9

Tips for Windows User to Set up GD(dynamic graphic lib) with PHP.

When i run following function, which terminates at

error message is : undefined function imagecreatefromjpeg();

no other code of the script gets executed.

In one word, you need to turn on gd lib,
which hold the implementation of imagecreatefromjpeg();

please follow below steps:

my php install dir is: c:/php/
first you must try to find:
c:/php/php.ini
c:/php/ext/php_gd2.dll(php 5)
c:/php/extension/php_gd2.dll(php 4)

The php_gd2.dll is included in a standard PHP installation for Windows,
however, it’s not enabled by default.
You have to turn it on,
You may simply uncomment the line «extension=php_gd2.dll» in php.ini and restart the PHP extension.

You may also have to correct the extension directory setting
from:
extension_dir = «./»
extension_dir = «./extensions»
To (FOR WINDOWS):
extension_dir = «c:/php/extensions»(php 4)
extension_dir = «c:/php/ext»(php 5)

This will clean up unnecessary jpeg header information which can cause trouble. Some cameras or applications write binary data into the headers which may result in ugly results such as strange colors when you resample the image later on.

This is from the jhead documentation: «-purejpg: Delete all JPEG sections that aren’t necessary for rendering the image. Strips any metadata that various applications may have left in the image.»

jhead got some other useful options as well.

Last night I posted the following note under move_upload_file and looked tonight to see if it got into the system. I happen to also pull up imagecreatefromjpeg and got reminded of many resize scripts in this section. Unfortunately, my experience was not covered by most of the examples below because each of them assumed less than obvious requirements of the server and browser. So here is the post again under this section to help others uncover the mystery in file uploading and resizing arbitrary sized images. I have been testing for several days with hundreds of various size images and it seems to work well. Many additional features could be added such as transparency, alpha blending, camera specific knowledge, more error checking. Best of luck.

I have for a couple of years been stymed to understand how to effectively load images (of more than 2MB) and then create thumbnails. My note below on general file uploading was an early hint of some of the system default limitations and I have recently discovered the final limit I offer this as an example of the various missing pieces of information to successfully load images of more than 2MB and then create thumbnails. This particular example assumes a picture of a user is being uploaded and because of browser caching needs a unique number at the end to make the browser load a new picture for review at the time of upload. The overall calling program I am using is a Flex based application which calls this php file to upload user thumbnails.

The secret sauce is:

1. adjust server memory size, file upload size, and post size
2. convert image to standard formate (in this case jpg) and scale

htaccess file:
php_value post_max_size 16M
php_value upload_max_filesize 6M

Источник

PHP ImageCreateFromString and file_get_contents

I am trying to make a function in PHP that will allow me to enter basically any URL and then runs some functions on it just as if a user was uploading on my server. SO I will resize and make some thumbnails but I need help just getting the image in a state that I can run my other codes on it. Another user on this site helped me get started with ImageCreateFromString() and file_get_contents()

Please note this code is missing a lot of stuff I am aware of, I am just trying to get the basic function working and then I will add in all the security measures

I tried this code below using a URL like this with the photo URL added to my script url:

But it shows nothing and not even an error

###### UPDATE #####

It seems it was a simple error on my part, something simple as checking for a POST request instead of a GET request, here is my new code below.

I have a couple of issues,

1) I am using imagejpeg($image, null, 100); and I am wondering, should I be using something else? Does it require the source image to be a jpg or will it work with any image? I need to allow the main types (jpg, jpeg, gif, png)

2) same as above question but for when showing the image on screen I have header set to this: header(‘Content-Type: image/jpeg’); should it not be jpg for other type of images?

3) Is there a way that I can make sure that the source URL passed in is an actual image and do whatever I want if it is not a image, like show my own error or do my own code once it detect that the URL is not a valid image url

Источник

imagecreatefrompng

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecreatefrompng — Создаёт новое изображение из файла или URL

Описание

imagecreatefrompng() возвращает идентификатор изображения, представляющего изображение полученное из файла с заданным именем.

Список параметров

Путь к изображению PNG.

Возвращаемые значения

Возвращает объект изображения в случае успешного выполнения или false в случае возникновения ошибки.

Список изменений

ВерсияОписание
8.0.0В случае успешного выполнения функция теперь возвращает экземпляр GDImage ; ранее возвращался ресурс ( resource ).

Примеры

Пример #1 Пример обработки ошибки при загрузке PNG

header ( ‘Content-Type: image/png’ );

$img = LoadPNG ( ‘bogus.image’ );

Результатом выполнения данного примера будет что-то подобное:

imagecreatefromstring no jpeg support in this php build. Смотреть фото imagecreatefromstring no jpeg support in this php build. Смотреть картинку imagecreatefromstring no jpeg support in this php build. Картинка про imagecreatefromstring no jpeg support in this php build. Фото imagecreatefromstring no jpeg support in this php build

User Contributed Notes 7 notes

If you’re trying to load a translucent png-24 image but are finding an absence of transparency (like it’s black), you need to enable alpha channel AND save the setting. I’m new to GD and it took me almost two hours to figure this out.

I had the same problem as jboyd1189 at yahoo dot com but I solve d it allocating more memory dynamically.

The approach I used to solve the problem is:

1-Calculate the memory required by the image
2-Set the new memory_limit value
3-Create the PNG image and thumbnail
4-Restore the original value

Because gd and imagick do not support animated PNG (at this moment), i wrote a simple function to determine if given PNG is APNG or not. It does not validate PNG, only checks whenever «acTL» chunk appears before «IDAT» like the specification says: https://wiki.mozilla.org/APNG_Specification

When using imagecreatepng with alpha blending you will lose the blending.

This will create a true colour image then copy the png image to this true colour image and retain alpha blending.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *