【问题标题】:Working with (and saving) various image filetypes?使用(和保存)各种图像文件类型?
【发布时间】:2012-05-24 18:36:42
【问题描述】:

我正在编写一个用于裁剪图像的脚本。它正在处理jpgs。但是有没有办法让它适用于各种文件类型(bmp、png、gif)而不通过各种 if 子句?

//create the crop
// Original image
$filename = 'uploads/'.$image_name;

$endname = 'uploads/thumbnails/'.$image_name;

// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);

// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 0;
$top = 0;

// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 200;
$crop_height = 200;

// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $crop_width, $crop_height);
imagejpeg($canvas, $endname, 100);

我尝试用imagecreate 替换imcreatefromjpeg,但没有奏效。

【问题讨论】:

  • 您可能需要考虑为此目的使用ImageMagick - 它比 GD2 灵活得多。

标签: php image crop


【解决方案1】:

imagecreatefromstring 自动检测文件类型,但它需要图像数据作为字符串,但你总是可以这样做

$current_image = imagecreatefromstring(file_get_contents($filename));

【讨论】:

    【解决方案2】:

    scr - 用于您的源文件 dest - 结果文件

         $size = getimagesize($src); 
    
            // Detect file format from MIME-information, detected by getimagesize() function
            // And select proper imagecreatefrom()-function.
    $format = strtolower(substr($size['mime'], strpos($size['mime'], '/')+1));
    $icfunc = "imagecreatefrom" . $format;
    if (!function_exists($icfunc)){
        echo "Function $icfunc doesn't exists!");
    }
    
        //Here is the magic: We call function, which name is value of variable
    $isrc = $icfunc($src);
    
        // Create new img
    $idest = imagecreatetruecolor($width_dest, $height_dest);
    
        // Copy src img to dest img with resizing
    imagecopyresampled(
        $idest, $isrc,  // dest & src img ident
        0,0,      // dest img (x,y) top left corner
        0,0,      // src img (x,y) top left corner
        $width_dest, $height_dest,
        $width_src, $height_src
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-30
      • 2018-09-04
      • 1970-01-01
      • 2012-10-24
      • 1970-01-01
      • 2011-07-07
      • 1970-01-01
      • 2011-09-28
      相关资源
      最近更新 更多