How to avoid black background when rotating an image 45 degree using PHP?

☆樱花仙子☆ 提交于 2019-12-22 07:56:06

问题


Hi I have to flip a thumpnail image before merge it with another jpeg file. but when I rotate 45 degree using php. It shows a black background. how can I avoid that. any body can help me.


回答1:


<?
$image = "130.jpg";
$degrees = 25;
for($i=0;$i<count($data);$i++){
    $ext = "";
    $extarr = "";
    $extarr = explode(".", $data[$i]['name']);
    $ext = array_pop($extarr);
    if($ext == "png"){
        $rotate = imagecreatefrompng("images/".$data[$i]['name']);
        $transColor = imagecolorallocatealpha($rotate, 255, 255, 255, 270);
        $watermark1[$i] = imagerotate($rotate, ((360-$degrees)%360), $transColor);
    }
}

function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opct){
    $w = imagesx($src_im);
    $h = imagesy($src_im);
    $cut = imagecreatetruecolor($src_w, $src_h);
    imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
    imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
    imagecopymerge($dst_im, $cut, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, (100 - $opct));
}


for($i=0; $i<count($watermark1); $i++){
    if($i == 0) imagecopymerge_alpha($image, $watermark1[$i], $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, $opacity);
    else imagecopymerge_alpha($image, $watermark1[$i], ($i*$dest_x)*3, ($i*$dest_y)*15, 0, 0, $watermark_width, $watermark_height, $opacity);
    imagedestroy($watermark1[$i]);
}
header("content-type: image/png");
imagepng($image);
imagedestroy($image);
?>

Also, do your watermark images have alpha channel or are they fully opaque?




回答2:


Well, if you are generating a jpg, using PHP GD you set the color of the background as the third option of the function imagerotate. In this example I'm gonna assume that you are rotating a jpg image $filename by an arbitrary $angle degrees, and you want a white background, i.e. color code 16777215:

$rotatedImage = imagerotate(imagecreatefromjpeg($filename), ((360-$angle)%360), 16777215);

black is color code 0, which is default, and the rest of the color gamma is in between the two, so you just need to decide which background color you would like

EDIT: for transparent backgrounds, if you are generating a png you would do:

$destimg = imagecreatefromjpeg($filename);
$transColor = imagecolorallocatealpha($destimg, 255, 255, 255, 127);
$rotatedImage = imagerotate($destimg, ((360-$angle)%360), $transColor);

Hope that helps



来源:https://stackoverflow.com/questions/3012051/how-to-avoid-black-background-when-rotating-an-image-45-degree-using-php

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