php 调整大小脚本不适用于透明 gif

发布于 2024-07-16 17:33:31 字数 1284 浏览 11 评论 0原文

我怎样才能让它适用于透明 gif 和 png ?

function resizeImage($image,$newImage,$target_width,$target_height, $type="") {
    if (is_file($image)) {
        if($type == ".gif"){
            $image_org=@imagecreatefromgif($image);
        }else{
            $image_org=@imagecreatefromjpeg($image);
        }
        if ($image_org) {
            list($w,$h,$type,$attr) = getimagesize($image);
            $factor=C_Image_Custom::calcRescaleFactor($w,$h,$target_width,$target_height);

            if ($factor>1) {
                $image_w = $w / $factor;
                $image_h = $h / $factor;
            } else {
                $image_w = $w;
                $image_h = $h;
            }       

        //Note: PHP with GD2.0 required for imagecreatetruecolor
        $img_copy = imagecreatetruecolor($image_w, $image_h);
        imagecopyresampled($img_copy, $image_org, 0, 0, 0, 0, $image_w, $image_h, $w, $h);

            if (@imagejpeg($img_copy, $newImage, 80)) {
                chmod($newImage,0777);
            }   else {
                echo("<b>Error: </b>Unable to create image $newImage. Check directory permissions.");
            }   

          imagedestroy($image_org);
            imagedestroy($img_copy);
        }   
    }   

How Can I get this working for transparent gif's and png's?

function resizeImage($image,$newImage,$target_width,$target_height, $type="") {
    if (is_file($image)) {
        if($type == ".gif"){
            $image_org=@imagecreatefromgif($image);
        }else{
            $image_org=@imagecreatefromjpeg($image);
        }
        if ($image_org) {
            list($w,$h,$type,$attr) = getimagesize($image);
            $factor=C_Image_Custom::calcRescaleFactor($w,$h,$target_width,$target_height);

            if ($factor>1) {
                $image_w = $w / $factor;
                $image_h = $h / $factor;
            } else {
                $image_w = $w;
                $image_h = $h;
            }       

        //Note: PHP with GD2.0 required for imagecreatetruecolor
        $img_copy = imagecreatetruecolor($image_w, $image_h);
        imagecopyresampled($img_copy, $image_org, 0, 0, 0, 0, $image_w, $image_h, $w, $h);

            if (@imagejpeg($img_copy, $newImage, 80)) {
                chmod($newImage,0777);
            }   else {
                echo("<b>Error: </b>Unable to create image $newImage. Check directory permissions.");
            }   

          imagedestroy($image_org);
            imagedestroy($img_copy);
        }   
    }   

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

魄砕の薆 2024-07-23 17:33:31

这个函数非常适合我调整 jpg 和透明(或非)gif 的大小:

function resizeImage($originalImage, $toWidth, $toHeight, $isJPG)
{
    // Get the original geometry and calculate scales
    list($width, $height) = getimagesize($originalImage);
    $xscale = $width / $toWidth;
    $yscale = $height / $toHeight;

    // Recalculate new size with default ratio
    if ($yscale > $xscale) {
        $new_width = round($width * (1 / $yscale));
        $new_height = round($height * (1 / $yscale));
    } else {
        $new_width = round($width * (1 / $xscale));
        $new_height = round($height * (1 / $xscale));
    }

    // Resize the original image
    if ($isJPG) {
        $imageResized = imagecreatetruecolor($new_width, $new_height);
        $imageTmp = imagecreatefromjpeg($originalImage);
        imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    } else {
        //$imageResized = imagecreatetruecolor($new_width, $new_height);
        //$imageTmp = imagecreatefromgif ($originalImage);
        //imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

        # what follows is for resizing a gif, transparent or not
        # http://ru2.php.net/imagecopyresampled
        # load/create images
        $imageTmp = imagecreatefromgif($originalImage);
        $imageResized = imagecreatetruecolor($new_width, $new_height);
        imagealphablending($imageResized, false);

        # get and reallocate transparency-color
        $transindex = imagecolortransparent($imageTmp);
        if ($transindex >= 0) {
            $transcol = imagecolorsforindex($imageTmp, $transindex);
            $transindex = imagecolorallocatealpha(
                $imageResized,
                $transcol['red'],
                $transcol['green'],
                $transcol['blue'],
                127
            );
            imagefill($imageResized, 0, 0, $transindex);
        }

        # resample
        imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

        # restore transparency
        if ($transindex >= 0) {
            imagecolortransparent($imageResized, $transindex);
            for ($y = 0; $y < $new_height; ++$y) {
                for ($x = 0; $x < $new_width; ++$x) {
                    if (((imagecolorat($imageResized, $x, $y) >> 24) & 0x7F) >= 100) {
                        imagesetpixel(
                            $imageResized,
                            $x,
                            $y,
                            $transindex
                        );
                    }
                }
            }

        }
        # save GIF
        imagetruecolortopalette($imageResized, true, 255);
        imagesavealpha($imageResized, false);
    }
    return $imageResized;
}

原始函数来自 PhpToys 1.0,使用透明 .gif 的部分来自 此 PHP 文档注释

This function works perfectly for me for resizing jpg's and transparent (or not) gif's:

function resizeImage($originalImage, $toWidth, $toHeight, $isJPG)
{
    // Get the original geometry and calculate scales
    list($width, $height) = getimagesize($originalImage);
    $xscale = $width / $toWidth;
    $yscale = $height / $toHeight;

    // Recalculate new size with default ratio
    if ($yscale > $xscale) {
        $new_width = round($width * (1 / $yscale));
        $new_height = round($height * (1 / $yscale));
    } else {
        $new_width = round($width * (1 / $xscale));
        $new_height = round($height * (1 / $xscale));
    }

    // Resize the original image
    if ($isJPG) {
        $imageResized = imagecreatetruecolor($new_width, $new_height);
        $imageTmp = imagecreatefromjpeg($originalImage);
        imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    } else {
        //$imageResized = imagecreatetruecolor($new_width, $new_height);
        //$imageTmp = imagecreatefromgif ($originalImage);
        //imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

        # what follows is for resizing a gif, transparent or not
        # http://ru2.php.net/imagecopyresampled
        # load/create images
        $imageTmp = imagecreatefromgif($originalImage);
        $imageResized = imagecreatetruecolor($new_width, $new_height);
        imagealphablending($imageResized, false);

        # get and reallocate transparency-color
        $transindex = imagecolortransparent($imageTmp);
        if ($transindex >= 0) {
            $transcol = imagecolorsforindex($imageTmp, $transindex);
            $transindex = imagecolorallocatealpha(
                $imageResized,
                $transcol['red'],
                $transcol['green'],
                $transcol['blue'],
                127
            );
            imagefill($imageResized, 0, 0, $transindex);
        }

        # resample
        imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

        # restore transparency
        if ($transindex >= 0) {
            imagecolortransparent($imageResized, $transindex);
            for ($y = 0; $y < $new_height; ++$y) {
                for ($x = 0; $x < $new_width; ++$x) {
                    if (((imagecolorat($imageResized, $x, $y) >> 24) & 0x7F) >= 100) {
                        imagesetpixel(
                            $imageResized,
                            $x,
                            $y,
                            $transindex
                        );
                    }
                }
            }

        }
        # save GIF
        imagetruecolortopalette($imageResized, true, 255);
        imagesavealpha($imageResized, false);
    }
    return $imageResized;
}

The original function is from PhpToys 1.0, and the part that works with transparent .gifs comes from this PHP docs comment.

陌路终见情 2024-07-23 17:33:31

我遇到了同样的问题,透明度不适用于 PNG,当它与 PNG 配合使用时,它就不适用于 GIF,我一整天都在寻找解决方案,直到我找到这个函数“Maxim's,智能调整图像大小"

$info = getimagesize($file);

switch ( $info[2] ) {
    case IMAGETYPE_GIF: $image = imagecreatefromgif($file); break;
    case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($file); break;
    case IMAGETYPE_PNG: $image = imagecreatefrompng($file); break;
    default: return false;
}

# This is the resizing/resampling/transparency-preserving magic
$image_resized = imagecreatetruecolor( $final_width, $final_height );

if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
    $transparency = imagecolortransparent($image);
    if ($transparency >= 0) {

        $transparent_color = imagecolorsforindex($image, $trnprt_indx);
        $transparency = imagecolorallocate($image_resized, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
        imagefill($image_resized, 0, 0, $transparency);
        imagecolortransparent($image_resized, $transparency);

    }
    elseif ($info[2] == IMAGETYPE_PNG) {

        imagealphablending($image_resized, false);
        $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
        imagefill($image_resized, 0, 0, $color);
        imagesavealpha($image_resized, true);

    }
}

imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $final_width, $final_height, $width_old, $height_old);

某些变量上只有一些小错误,所以你必须按如下所示分配它们以消除 $trnprt_indx 和 $trnprt_color 的错误

$trnprt_color['red'] = 255;
$trnprt_color['green'] = 255;
$trnprt_color['blue'] = 255;
$trnprt_indx = 127;

希望这会对您有所帮助

i had the same problem, transparency just don't work for PNG and when it work with PNG it just don't with GIF, I've been looking all day for a solution till i found this function "Maxim's, smart resize image"

$info = getimagesize($file);

switch ( $info[2] ) {
    case IMAGETYPE_GIF: $image = imagecreatefromgif($file); break;
    case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($file); break;
    case IMAGETYPE_PNG: $image = imagecreatefrompng($file); break;
    default: return false;
}

# This is the resizing/resampling/transparency-preserving magic
$image_resized = imagecreatetruecolor( $final_width, $final_height );

if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
    $transparency = imagecolortransparent($image);
    if ($transparency >= 0) {

        $transparent_color = imagecolorsforindex($image, $trnprt_indx);
        $transparency = imagecolorallocate($image_resized, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
        imagefill($image_resized, 0, 0, $transparency);
        imagecolortransparent($image_resized, $transparency);

    }
    elseif ($info[2] == IMAGETYPE_PNG) {

        imagealphablending($image_resized, false);
        $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
        imagefill($image_resized, 0, 0, $color);
        imagesavealpha($image_resized, true);

    }
}

imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $final_width, $final_height, $width_old, $height_old);

There is just small errors on some variables, so you have to assign them as below to remove errors for $trnprt_indx and $trnprt_color

$trnprt_color['red'] = 255;
$trnprt_color['green'] = 255;
$trnprt_color['blue'] = 255;
$trnprt_indx = 127;

Hope this will help you

北风几吹夏 2024-07-23 17:33:31

看起来您只输出到 jpeg - 它没有透明度。 如果要输出透明度,则需要输出gif或png。

如果你想用颜色替换透明度,我想你需要 php 函数 imagecolorallocatealpha

It looks like you're only outputting to jpeg - which doesn't have transparency. If you want to output the transparency, you need to output a gif or png.

If you want to replace the transparency with a colour, I think you want the php function imagecolorallocatealpha

冷月断魂刀 2024-07-23 17:33:31

为什么只有jpeg?

这也适用于 gif:

if($type == ".gif"){
                    $image_org=@imagecreatefromgif($image);
            }else{
                    $image_org=@imagecreatefromjpeg($image);
            }

Why only a jpeg?

This is also for gif:

if($type == ".gif"){
                    $image_org=@imagecreatefromgif($image);
            }else{
                    $image_org=@imagecreatefromjpeg($image);
            }
标点 2024-07-23 17:33:31

这确实很旧,但以防万一其他人像我一样难以理解,这里是对我有用的解释:

<?php
$sourceImage = imagecreatefromgif('./enjoy.gif');
        
$newWidth = 220;
$newHeight = 120;

//Blank canvas
$destImage = imagecreatetruecolor($newWidth, $newHeight);

$transColorIndex = imagecolortransparent($sourceImage); 
// Returns the index of the transparent color: 119

$transRGBColor = imagecolorsforindex($sourceImage, $transColorIndex); 
//Returns the RGB of the index color: [red] => 255 [green] => 255 [blue] => 255 [alpha] => 127 
//In this case it's white but can be anaything

$transGdColor = imagecolorallocate($destImage, $transRGBColor['red'], $transRGBColor['green'], $transRGBColor['blue']); 
// Returns: 16777215   //A GD color identifier created with imagecolorallocate().

imagefill($destImage, 0, 0, $transGdColor);
//Fills the blank image with that color

imagecolortransparent($destImage, $transGdColor);
//Sets that color as transparent

//Resample
imagecopyresampled($destImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($sourceImage), imagesy($sourceImage));

header ( 'Content-type:image/gif' );
imagegif($destImage);

This is really old but in case some else is struggling to understand as much as I did here's what worked for me with explanation:

<?php
$sourceImage = imagecreatefromgif('./enjoy.gif');
        
$newWidth = 220;
$newHeight = 120;

//Blank canvas
$destImage = imagecreatetruecolor($newWidth, $newHeight);

$transColorIndex = imagecolortransparent($sourceImage); 
// Returns the index of the transparent color: 119

$transRGBColor = imagecolorsforindex($sourceImage, $transColorIndex); 
//Returns the RGB of the index color: [red] => 255 [green] => 255 [blue] => 255 [alpha] => 127 
//In this case it's white but can be anaything

$transGdColor = imagecolorallocate($destImage, $transRGBColor['red'], $transRGBColor['green'], $transRGBColor['blue']); 
// Returns: 16777215   //A GD color identifier created with imagecolorallocate().

imagefill($destImage, 0, 0, $transGdColor);
//Fills the blank image with that color

imagecolortransparent($destImage, $transGdColor);
//Sets that color as transparent

//Resample
imagecopyresampled($destImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($sourceImage), imagesy($sourceImage));

header ( 'Content-type:image/gif' );
imagegif($destImage);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文