在PHP中将图像分为三种尺寸

时间:2022-10-31 10:34:54

I am actually trying to make an image into three sizes and then storing them in the server folder with different names. I am getting this image data in Base64 encoded format through the mobile client side. Here is the code where I am trying to convert the image into three images.

我实际上试图将图像分成三种尺寸,然后将它们存储在具有不同名称的服务器文件夹中。我通过移动客户端获取Base64编码格式的图像数据。这是我试图将图像转换为三个图像的代码。

This is the PHP file where I am receiving data.

这是我接收数据的PHP文件。

$uploadPath  = 'C:/xampp/htdocs/OSFiles/of-images/images/';

if(!is_dir($uploadPath))
    mkdir($uploadPath,true) or trigger_error("Can't Create Folder");

$file   = tempnam($uploadPath, 'image');
$fp     = fopen($file, 'wb');
fwrite($fp, $binary);   //$binary is--> I am reading the image in binary as I am getting the photo data in base64 encoded format through mobile client side. So I decoded it to binary.

fclose($fp);

$result1 = mysql_query("INSERT INTO oc_t_item_resource(fk_i_item_id, s_name,s_extension,s_content_type, s_path)
        VALUES('$lastid','$s_name','$extension','$s_content_type','$imagepath')");

$imagelastid = mysql_insert_id();

// Create normal size
$normal_path = $path = $uploadPath . $imagelastid . '.jpg' ;
$size = explode('x', '640x480') ;

ImageResizer::fromFile($file)->resizeTo($size[0], $size[1])->saveToFile($path) ;

// Create preview
$path = $uploadPath . $imagelastid . '_preview.jpg' ;
$size = explode('x', '480x340') ;
ImageResizer::fromFile($file)->resizeTo($size[0], $size[1])->saveToFile($path) ;

// Create thumbnail
$path = $uploadPath . $imagelastid . '_thumbnail.jpg' ;
$size = explode('x', '240x200') ;
ImageResizer::fromFile($file)->resizeTo($size[0], $size[1])->saveToFile($path) ;

This is my ImageResizer class which is in ImageResizer.php file.

这是我在ImageResizer.php文件中的ImageResizer类。

<?php
    class ImageResizer {

        public static function fromFile($imagePath) {
            return new ImageResizer($imagePath);
        }

        private $im;

        private function __construct($imagePath) {
            if(!file_exists($imagePath)) throw new Exception("$imagePath does not exist!");
            if(!is_readable($imagePath)) throw new Exception("$imagePath is not readable!");
            if(filesize($imagePath)==0) throw new Exception("$imagePath is corrupt or broken!");

            if(osc_use_imagick()) {
                $this->im = new Imagick($imagePath);
            } else {
                $content = file_get_contents($imagePath);
                $this->im = imagecreatefromstring($content);
            }

            return $this;
        }

        public function __destruct() {
            if(osc_use_imagick()) {
                $this->im->destroy();
            } else {
                imagedestroy($this->im);
            }
        }

        public function resizeTo($width, $height) {
            if(osc_use_imagick()) {
                $bg = new Imagick();
                $bg->newImage($width, $height, 'white');

                $this->im->thumbnailImage($width, $height, true);
                $geometry = $this->im->getImageGeometry();

                $x = ( $width - $geometry['width'] ) / 2;
                $y = ( $height - $geometry['height'] ) / 2;

                $bg->compositeImage( $this->im, imagick::COMPOSITE_OVER, $x, $y );
                $this->im = $bg;
            } else {
                $w = imagesx($this->im);
                $h = imagesy($this->im);

                if(($w/$h)>=($width/$height)) {
                    //$newW = $width;
                    $newW = ($w > $width)? $width : $w;
                    $newH = $h * ($newW / $w);
                } else {
                    //$newH = $height;
                    $newH = ($h > $height)? $height : $h;
                    $newW = $w * ($newH / $h);
                }

                $newIm = imagecreatetruecolor($width,$height);//$newW, $newH);
                imagealphablending($newIm, false);
                $colorTransparent = imagecolorallocatealpha($newIm, 255, 255, 255, 127);
                imagefill($newIm, 0, 0, $colorTransparent);
                imagesavealpha($newIm, true);
                imagecopyresampled($newIm, $this->im, (($width-$newW)/2), (($height-$newH)/2), 0, 0, $newW, $newH, $w, $h);
                imagedestroy($this->im);

                $this->im = $newIm;
            }
            return $this;
        }

        public function saveToFile($imagePath) {
            if(file_exists($imagePath) && !is_writable($imagePath)) throw new Exception("$imagePath is not writable!");
            if(osc_use_imagick()) {
                $this->im->setImageFileName($imagePath);
                $this->im->writeImage($imagePath);
            } else {
                imagejpeg($this->im, $imagePath);
            }
        }

        public function show() {
            header('Content-Disposition: Attachment;filename=image.jpg');
            header('Content-type: image/jpg');
            if(osc_use_imagick()) {
            } else {
                imagepng($this->im);
            }
        }
    }
?>

The image is not getting stored at all in the images folder. Where am I going wrong?

图像文件夹中根本没有存储图像。我哪里错了?

A code snippet with corrections would be appreciated.

我们将非常感谢带有更正的代码段。

(I am new to PHP, so please be gentle.)

(我是PHP的新手,所以请保持温和。)

1 个解决方案

#1


1  

I would suggest using error_reporting( -1 ) when searching for bugs. Then you just follow the messages and fix all the errors.

我建议在搜索bug时使用error_reporting(-1)。然后,您只需按照消息并修复所有错误。

You skipped one parameter for mkdir. $mode is ignored on Windows, but it should be passed anyway in order to get to the $recursive parameter: mkdir( $uploadPath, 0777, true ).

您跳过了mkdir的一个参数。在Windows上忽略$ mode,但无论如何都应该传递它以获得$ recursive参数:mkdir($ uploadPath,0777,true)。

Also, you should have a function osc_use_imagick included somewhere. I don't have it so I had to change conditions from if( osc_use_imagick() ) to if( function_exists( 'osc_use_imagick' ) && osc_use_imagick() ).

此外,你应该在某处包含一个函数osc_use_imagick。我没有它所以我不得不将条件从if(osc_use_imagick())更改为if(function_exists('osc_use_imagick')&& osc_use_imagick())。

And by the way, you forget to delete your temporary file after all the resizes. Add unlink( $file ) to the end of the script.

顺便说一句,在所有调整大小后,您忘记删除临时文件。将unlink($ file)添加到脚本的末尾。

#1


1  

I would suggest using error_reporting( -1 ) when searching for bugs. Then you just follow the messages and fix all the errors.

我建议在搜索bug时使用error_reporting(-1)。然后,您只需按照消息并修复所有错误。

You skipped one parameter for mkdir. $mode is ignored on Windows, but it should be passed anyway in order to get to the $recursive parameter: mkdir( $uploadPath, 0777, true ).

您跳过了mkdir的一个参数。在Windows上忽略$ mode,但无论如何都应该传递它以获得$ recursive参数:mkdir($ uploadPath,0777,true)。

Also, you should have a function osc_use_imagick included somewhere. I don't have it so I had to change conditions from if( osc_use_imagick() ) to if( function_exists( 'osc_use_imagick' ) && osc_use_imagick() ).

此外,你应该在某处包含一个函数osc_use_imagick。我没有它所以我不得不将条件从if(osc_use_imagick())更改为if(function_exists('osc_use_imagick')&& osc_use_imagick())。

And by the way, you forget to delete your temporary file after all the resizes. Add unlink( $file ) to the end of the script.

顺便说一句,在所有调整大小后,您忘记删除临时文件。将unlink($ file)添加到脚本的末尾。