根据需要使用imagecreatefromjpeg / png / gif / bmp添加水印时,为什么尺寸会变大?

时间:2016-08-09 19:28:23

标签: php image image-uploading watermark image-size

我的主题是使用PHP代码为图像添加水印。示例在这里http://php.net/manual/en/image.examples-watermark.php

我遇到的一个问题是,上面提到的例子只处理JPEG图像,因为它使用了imagecreatefromjpeg()函数。

我使用了这个功能,我不记得从哪里得到它。它创建了其他类型的图像png,bmp和gif。

function imageCreateFromAny($filepath){
    $type = exif_imagetype($filepath); // [] if you don't have exif you could use getImageSize()
    $allowedTypes = array(
        1,  // [] gif
        2,  // [] jpg
        3,  // [] png
        6   // [] bmp
    );
    if (!in_array($type, $allowedTypes)) {
        return false;
    }
    switch ($type) {
        case 1 :

            $im = imageCreateFromGif($filepath);
        break;
        case 2 :

            $im = imageCreateFromJpeg($filepath);
        break;
        case 3 :

            $im = imageCreateFromPng($filepath);
        break;
        case 6 :

            $im = imageCreateFromBmp($filepath);
        break;
    }   
    return $im; 
}

问题:函数的输出图像是一个图像,其尺寸数乘以4,我的意思是尺寸变大4倍左右。例如,如果函数接收到图像为94K,则输出大约380K。

我想解决最大化大小编号的问题,我想获得与图像大小输入到函数imageCreateFromAny($ filepath)之前相同的图像大小

提示: 以下函数调用上述函数

function Stamp($filename){




        // Load the stamp and the photo to apply the watermark to
        $stamp = imagecreatefrompng('../../style/images/stamp1.png');
//        $im = imagecreatefromjpeg('../../gallery/black-white/'.$filename);
        $im = imageCreateFromAny('../../gallery/black-white/'.$filename);


        // Set the margins for the stamp and get the height/width of the stamp image
        $marge_right = 10;
        $marge_bottom = 10;
        $sx = imagesx($stamp);
        $sy = imagesy($stamp);

        // Copy the stamp image onto our photo using the margin offsets and the photo 
        // width to calculate positioning of the stamp. 
        imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

        // Output and free memory
//        header('Content-type: image/png');
//        imagepng($im);
        $filename_new = '../../gallery/black-white/'.$filename.'';
//        if (move_uploaded_file(imagepng($im), '../../gallery/black-white/2'   )) 
        imagepng($im, $filename_new);
        imagedestroy($im);


}

1 个答案:

答案 0 :(得分:3)

您将图像保存为PNG,是的,通常比JPEG大得多,但质量也更高。 JPEG是有损格式,它会丢弃较小文件大小的质量。 PNG是一种无损格式,它保留所有可能的信息,并尝试尽可能多地压缩数据。对于具有大量细节的图像,这将导致尺寸大于JPEG且质量设置较低。