PHP - Rotate image with GD gives black borders

断了今生、忘了曾经 提交于 2019-12-23 15:23:48

问题


I am trying to rotate and save an image. The rotation is based on the EXIF data. I have tried the following, which all give a black border around it:

Where the original looks like this:

$orientation = array_values([0, 0, 0, 180, 0, 0, -90, 0, 90])[@exif_read_data($imagePath)['Orientation'] ?: 0];

$source = imagecreatefromjpeg($imagePath);
$resource = imagerotate($source, $orientation, 0);
imagejpeg($resource, $image, 100);

I have also tried adding imagealphablending($resource, true); and imagesavealpha($resource, true); as proposed in Black background when rotating image with PHP, but to no avail; the border remains.

Then I tried creating the image with imagecreatetruecolor():

$imageSizes = getimagesize($image);
$oldWidth  = $imageSizes[0];
$oldHeight = $imageSizes[1];

$orientation = array_values([0, 0, 0, 180, 0, 0, -90, 0, 90])[@exif_read_data($image)['Orientation'] ?: 0];

$source = imagecreatefromjpeg($imagePath);
$resource = imagerotate($source, $orientation, 0);

$newWidth  = $oldWidth;
$newHeight = $oldHeight;

if ($orientation !== 180 && $orientation !== 0) {
    $newWidth  = $oldHeight;
    $newHeight = $oldWidth;
}

$imageResized = imagecreatetruecolor($newWidth, $newHeight); 

imagecopyresampled ($imageResized, $resource, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight); 
imagejpeg($imageResized, $image, 100);

But I just can't seem to get it work. Is anyone able to help me with this?


回答1:


I've found this problem today in PHP for Windows. The borders only seem to get added when you do a 0 or 360 degree rotation. I don't get the borders with a 180 degree rotation. So, just check to see if orientation is non-zero and only rotate if necessary.

... if ($orientation !== 0) $resource = imagerotate($source, $orientation, 0); else $resource = $source; end ...




回答2:


this isnt an answer.. it may help you, or it may not

i have tested your code, and work fine for me

also, using your image it wont give me your problem.

as i can see, your result image, that with black border, have a diference with the original.. look the left border, the top dog is croped, and that difference is the black border



来源:https://stackoverflow.com/questions/40630725/php-rotate-image-with-gd-gives-black-borders

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!