The imagewebp function fails without generating any errors - php

I want to convert a folder of jpeg images to webp format in another folder. I'm using the imagewebp function in the GD library. The code just halts when the function is called. Although the file is actually created it is of zero length. No errors are thrown.
gd_info shows version 2.1 with WebP support as 1.
php version 5.6
Everything works if I change to imagepng() so the library is installed and working.
I've tried on individual small images in case it was a memory issue but still has the same problem.
Also tried imagecreatefromjpeg instead of imagecreatefromstring but same.
Removed the quality filter to default (eg omitted the 65) but the same effect.
I also tried outputting a single file directly to the browser. This works with imagepng, but I get a 404 error with imagewebp
$jpgfiles = glob ('jpegs/*.jpg');
echo "<p>" . sizeof( $jpgfiles ) . " files found. </p>"; // Shows 7 files
foreach($jpgfiles as $j) {
echo "<p>Found $j</p>"; // Shows first found file
$filename = substr( $j, 6, -4) . '.webp'; // Keep the same filename but change extension
echo "<p>$filename</p>";
$jpgimage = imagecreatefromstring( file_get_contents( $j ) );
if( !$jpgimage ) die ("Failed on imagecreatefromstring");
if( $webpimage = imagewebp( $jpgimage, 'webps/' . $filename, 65 )) echo "$filename created"; // This is never echo'd
else die ("Failed on imagewebp"); // Doesn't die either
imagedestroy ( $jpgimage );
}
I expected the images to be created but program execution stops. The error log does not contain any information. The die command is never invoked. The webp file is created but is of zero length.

Related

Warning: filesize(): stat failed for..error

i have this code:
$album_name = $row['album'];
if(!file_exists("cdcovers/$album_name.jpg") && filesize($album_name) > 5){
//gravar as imagens
$imageString = file_get_contents(LastFMArtwork::getArtwork($row['artist'], $row['album'], true, "large"));
$save = file_put_contents('/home/link/public_html/cdcovers/'.$row['album'].'.jpg',$imageString);
}
but i gives an error(Warning: filesize(): stat failed for...) if the image is not there,
my ideia was if the file exists and is bigger then 5kb then do nothing if it is 4kb or below save image, even if a file exists with 0kb.
Base on what I understand you want to create an image if it does not exist or update the image if it is smaller than 5kb.
In short, filesize will yield the warning if you give it a file that does not exists but there are a few more issues with the original code:
The condition block is wrong. The function filesize returns the size in bytes and 5kb is ~5,000 bytes.
The wrong comparison operator is also been use. The less than operator < should be used instead greater than operator >.
The code attempts to check the size of a file when it does not exist.
You are referencing different file paths in the condition block.
I modified the sample code to store the absolute path to the image in a variable and reference it where needed, fixed the bytes comparison and updated the condition block requirements to prevent the filesize warning.
Please review the updated code below:
$albumCoverImg = '/home/link/public_html/cdcovers/' . $row['album'] . '.jpg';
$minSize = 5 * 1000; // 5KB
$fileExist = is_file($albumCoverImg);
if (!$fileExist || ($fileExist && filesize($albumCoverImg) < $minSize)) {
//gravar as imagens
$imageString = file_get_contents(LastFMArtwork::getArtwork($row['artist'], $row['album'], true, "large"));
$save = file_put_contents($albumCoverImg, $imageString);
}
You have to check if the file exists before to check its size.
If "cdcovers/$album_name.jpg" and $album_name are different files, you also have to check the second.
if (!file_exists("cdcovers/$album_name.jpg") &&
file_exists($album_name) &&
filesize($album_name) > 5) {
If the files are the same, it's the error (missing folder and file extension).
Also, you save the file with an absolute path : '/home/link/public_html/cdcovers/'.$row['album'].'.jpg'. It could differ from "cdcovers/$album_name.jpg" (depending of the current folder's script execution). You may use the absolute path, of __dir__ constant to be relative to your current folder.
You may use variables to store filename and limit errors by writing them multiple times :
$filename = '/home/link/public_html/cdcovers/'.$row['album'].'.jpg' ;
if (!file_exists($filename) ||
(file_exists($filename) && filesize($filename) < 5000)) {
file_put_contents($filename, ...);
}
Please also note that filesize() returns the size in bytes, not in Kb.

How to processing an image downloaded from AWS S3 with Laravel 5?

I want download an image from AWS S3 and process it with php. I am using "imagecreatefromjpeg" and "getimagesize" to process my image but it seem that
Storage::disk('s3')->get(imageUrlonS3);
retrieve the image in binary and is giving me errors. This is my code:
function createSlices($imagePath) {
//create transform driver object
$im = imagecreatefromjpeg($imagePath);
$sizeArray = getimagesize($imagePath);
//Set the Image dimensions
$imageWidth = $sizeArray[0];
$imageHeight = $sizeArray[1];
//See how many zoom levels are required for the width and height
$widthLog = ceil(log($imageWidth/256,2));
$heightLog = ceil(log($imageHeight/256,2));
//more code here to slice the image
.
.
.
.
}
// ex: https://s3-us-west-2.amazonaws.com/bucketname/image.jpg
$content = Storage::disk('s3')->get(imageUrlonS3);
createSlices($content);
What am I missing here ?
Thanks
I think you are right in your question what the problem is - the get method returns the source of the image of itself, not the location of the image. When you pass that to createSlices, you're passing the binary data, not its file path. Inside of createSlices you call imagecreatefromjpeg, which expects a file path, not the image itself.
If this indeed the case, you should be able to use createimagefromstring instead of createimagefromjpeg and getimagesizefromstring instead of getimagesize. The functions createimagefromstring and getimagesizefromstring each expects the binary string of the image, which I believe is what you have.
Here's the relevant documentation:
createimagefromstring - http://php.net/manual/en/function.imagecreatefromstring.php
getimagesizefromstring - http://php.net/manual/en/function.getimagesizefromstring.php
Resulting code might look something like this:
function createSlices($imageData) {
$im = imagecreatefromstring($imageData);
$sizeArray = getimagesizefromstring($imageData);
//Everything else can probably be the same
.
.
.
.
}
$contents = Storage::disk('s3')->get($imageUrlOnS3);
createSlices($contents);
Please note I haven't tested this, but I believe from what I can see in your question and what I read in the documentation that this might just do it.

PHP - "FPDF error: Not a PNG file", but the image is

I'm currently running into a very odd issue with fpdf. I found a similar question with no answer: not a PNG file in FPDF. I have an image uploaded through a browser to my file server, and then pulled into a fpdf report. When this image is a png, I get the error: "FPDF error: Not a PNG file". I don't get any errors when the uploaded image is a jpg. This issue seemingly appeared overnight a few weeks ago.
Even stranger, it's only happening with new png's being uploaded. There was a png in a report that was generating fine. When I downloaded that png from the system and re-uploaded it, the errors appeared again.
Here are some of the steps I've taken while attempting to troubleshoot the issue:
I've made sure the image is actually a png (through its properties).
Nothing has changed with the way I've been saving the images, but here's the code:
$original = $time."_".$name."_o.".$extension;
$thumbnail = $time."_".$name."_t.".$extension;
include('SimpleImage.php');
$image = new SimpleImage();
$image->load($_FILES['file']['tmp_name']);
$image->save($A_path."images/".$original);
$image->resizeToHeight(200);
$image->save($A_path."images/thumbs/".$thumbnail);
$photo = "images/".$original;
$thumb = "images/thumbs/".$thumbnail;
I've checked to see if their were any changes to the PNG format or FPDF updates, with no luck.
I've converted a jpg that works into a png through gimp.
Converting a png to a jpg through gimp and then uploading the jpg to the system does not generate any errors.
WORKAROUND- I've gone ahead and converted png's to jpg's on save, rather than re-encoding the image. Thanks for the help.
Fixed it by changing the picture format manually to JPG and then repeating the process.
The error message indicates that there is something wrong with the first eight bytes of the file (the "png signature").
Use "od -c | head -1" to inspect the first 16 bytes. Every PNG file
begins with these:
211 P N G \r \n 032 \n \0 \0 \0 \r I H D R
If you prefer, use "xxd file.png | head -1" and expect to see this:
0000000: 8950 4e47 0d0a 1a0a 0000 000d 4948 4452 .PNG........IHDR
These 16 bytes are the PNG signature and the length and name of the first chunk. The first 8 bytes are the format
name, plus newlines (linefeeds) and carriage returns that are designed
to detect various transmission errors. The next 8 bytes are the beginning
of the IHDR chunk, which must be length=13 expressed as a 4-byte integer, and the name="IHDR".
See the PNG specification for details.
Check the depth of the image. FPDF supports 24bit depth (i'm not sure about 32bit depth), neither does it support alpha channel.
I'd try to reencode to png with ImageMagick (or paint.net under windows).
convert input.png -depth 8 +matte output.png
I found a crud solution that works for me but this will take little more space on your host. But you can determine which extension worked and delete the rest However its worth it.
First take the file contents and convert them to base64_encode.
Create an array of the file formats you want the file to be in "png","jpg","jpeg" and decode the base64 image looping through the file extensions. This recreates the image with three file extensions in your folder.
Use the
try{
}catch (Exception $e) {
}
to loop trough and find which image extension works and use it.
Here is my full code
$base64 = base64_encode(file_get_contents("full/domain/path/to/image"));
$f_ex = array('.png', '.jpg', '.jpeg'); //array of extensions to recreate
$path = "path/to/new/images"; //this folder will have there images.
$i = 0;
$end = 3;
while ($i < $end) {
$data = base64_decode($base64); //decode the image file from base64
$filename = "unique_but_memorable_filename(eg invoice id)" . $f_ex[$i]; //$f_ex loops through the file extensions
file_put_contents($path . $filename, $data); //we save our new images to the path above
$i++;
}
Inside your FPDF where your image is set, we loop through the images we recreated and see which one works and stop there
try {
$filename = "remember_unique_but_memorable_filename(eg invoice id)" . $f_ex[0];
$logo = "your domail.com where image was stored" . '/' . $path . $filename;
$pdf->Image($logo, 10, 17, 100, 100);
//Put your code here to delete the other image formats.
} catch (Exception $e) {
try {
$filename = "remember_unique_but_memorable_filename(eg invoice id)" . $f_ex[1];
$logo = "your domail.com where image was stored" . '/' . $path . $filename;
$pdf->Image($logo, 10, 17, 100, 100);
//Put your code here to delete the other image formats.
} catch (Exception $e) {
try {
$filename = "remember_unique_but_memorable_filename(eg invoice id)" . $f_ex[2];
$logo = "your domail.com where image was stored" . '/' . $path . $filename;
$pdf->Image($logo, 10, 17, 100, 100);
//Put your code here to delete the other image formats.
} catch (Exception $e) {
//if all the three formats fail, lets see the error
echo 'Message: ' . $e->getMessage();
}
}
}

my gd is enabled but still the imagecreatefromstring still not working

i want to transfer image from localhost to a server using post. i have a problem on my php who catch the image here is my code:
$string = "iVBORw0KGgoAAAANSUhEUgAAAO0AAAA2CAIAAACk1ok0AAAAAXNSR0IArs4c6QAAAARnQU1BAACx
jwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAUJSURBVHhe7Z2hVuwwEIaRSBxIBA+ARCKRSCQS
icQhkUgkj4BEIpFIHgGJRMJ/T+6dk9uybZr8k06ys2rhJNOZf74mkzbt7nz7xxVoX4Gd9kPwCFyB
b+fYIehBAee4hyx6DM6xM9CDAs5xD1n0GJxjZ6AHBZzjNrL4/Px8enr6+PjYhrvVvVyfY+Tm8PBw
J/rgT6WEPT09hWPpHUIpgwcHB3B7d3c3wz7OgYHCsdqWv6enaU2OxwSLpnkJm87xx8cHzKoeIgOy
2S5vb2+Xl5fi9mz7cYNGIQ4hJ5JQm+PEseHq6iojYXGXz8/P29vbiRSWH6LQw9nuLy8vA/8vLi5m
e40b3N3dWR50p31LTFM9jl9fX+/v78P8OPggPV9fXxkZ+rULBrDr6+u9vb1NAqG6YB1Lz85g9kAs
Z2dnRJW4npdMFxRPFDlGJkDMzc0NFiibkDo6OirMTeIALw6ABopwqkYwmeDcDj7jzMeYhLFZ9YiF
xjvkeBFYhfKh+0TlkL5KKHeDaOHh4SGeTOzPHhiwOuR4E1j4P8YY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c
oHQZozy72M9uUL8YpUjENaI3u2b42Q/HCB4oxz9hm41pSscMrb2LngJdcRzLhN8Okhffp3C5qI1G
ia+X422w/AO/8BouFT8hjwAAAABJRU5ErkJggg==";
that $string is my sample image
$img2 = base64_decode($string);
$img = imagecreatefromstring($img2);
if($img != false)
{
//this is the location and name you can use date time to create name if you want
//also put the path before the image if you want to save it to a folder ex. 'pics/image.jpg'
$path = "sample_upload/images/" . date("Y_m_d_H_i_s") . ".jpg";// put path here
$sampledate = date("Y_m_d_H_i_s");
echo $sampledate;
imagejpeg($img, $path.''.$sampledate.'.jpg');
//they can put db query here if they like to insert img path and email
}
the error is [31-Aug-2013 13:56:49 Asia/Manila] PHP Fatal error: Call to undefined function imagecreatefromstring()
the php version should be higher than 5

PHP imagejpeg() problems

I had an image upload script that worked on my little shared hosting, but just as I switched to Virt Ded, it immediately stopped working. After some research I determined the culprit to be the PHP function imagejpeg() - which was the last bit of code in the script.
It allows me to specify null as the filepath (in which case it prints it to the screen), but does not allow me to enter ANY filepath without return false.
Anybody know what is going on?
First I would see if the PHP install contains all the libgd stuff you need for imagejpeg().
You can check like this:
$extensions = get_loaded_extensions();
if( !in_array( 'gd', $extensions ) )
{
die "libgd is not loaded";
}
If that's good to go you can do something like:
$gd = gd_info();
while( list( $k, $v ) = each( $gd ) )
{
echo "$k: $v";
}
Make sure you see some jpeg stuff listed, if there is none you need some dependent libraries installed.

Categories