【问题标题】:php image upload not creating thumbnailphp图像上传不创建缩略图
【发布时间】:2012-09-21 06:23:15
【问题描述】:

大家好,我需要一些有关此代码的帮助,以便它上传正确大小的图像以及相应的缩略图:

    $file_path = $this->options['upload_dir'].$file_name;
    $new_file_path = $options['upload_dir'].$file_name;
    list($img_width, $img_height) = @getimagesize($file_path);

    if (!$img_width || !$img_height) {
        return false;
    }

    $scale = min(
        $options['max_width'] / $img_width,
        $options['max_height'] / $img_height
    );

    if ($scale > 1) {
        $scale = 1;
    }

    $new_width = 1280; //$new_width = $img_width * $scale;
    $new_height = 323; //$new_height = $img_height * $scale;        
    $new_img = @imagecreatetruecolor($new_width, $new_height);

    switch (strtolower(substr(strrchr($file_name, '.'), 1))) {
        case 'jpg':
        case 'jpeg':
            $src_img = @imagecreatefromjpeg($file_path);
            $write_image = 'imagejpeg';
            break;
        case 'gif':
            $src_img = @imagecreatefromgif($file_path);
            $write_image = 'imagegif';
            break;
        case 'png':
            $src_img = @imagecreatefrompng($file_path);
            $write_image = 'imagepng';
            break;
        default:
            $src_img = $image_method = null;
    }

    $success = $src_img && @imagecopyresampled(
        $new_img,
        $src_img,
        0, 0, 0, 0,
        $new_width,
        $new_height,
        $img_width,
        $img_height
    ) && $write_image($new_img, $options['upload_dir'] . $_GET['type'] . '.' . strtolower(substr(strrchr($file_name, '.'), 1)), 100);

    @imagedestroy($src_img);
    @imagedestroy($new_img);

我已经尝试添加这个:

    $success = $src_img && @imagecopyresampled(
        $new_img,
        $src_img,
        0, 0, 0, 0,
        192,
        50,
        $img_width,
        $img_height
    ) && $write_image($new_img, $options['upload_dir'] . $_GET['type'] . 'THUMB.' . strtolower(substr(strrchr($file_name, '.'), 1)), 100);

但它只是将同一张图片复制了两次,其高度和宽度与第一个相同:

Bob.jpg         800kb
BobTHUMB.jpg    800kb

【问题讨论】:

  • 让我问你一个问题。为什么人们在遇到问题时将所有代码发布到 SO,而不是创建小测试脚本来帮助我们帮助您?
  • 如果我这样做了......这将是一个很长的代码行,这反过来会关闭人们帮助查看整个 350 行代码:)
  • 不,我不是说将上面的代码合并成一行。您在创建缩略图时遇到问题?使用示例图像创建测试脚本,该脚本应该调用几个函数来向我们展示您想要实现的目标。真的不会超过 10 LOC。

标签: php file-upload thumbnails image-uploading


【解决方案1】:
$thm_img = @imagecreatetruecolor( 192, 50 );

$success = $src_img && @imagecopyresampled(
   $thm_img,
   $src_img,
   0, 0, 0, 0,
   192,
   50,
   $img_width,
   $img_height
) && $write_image($thm_img, $options['upload_dir'] . $_GET['type'] . 'THUMB.' . strtolower(substr(strrchr($file_name, '.'), 1)), 100);

【讨论】:

  • 乐于助人!问题是$new_img 资源已经分配在 1280x323 尺寸:)
  • 太棒了!很高兴知道。谢谢!
猜你喜欢
  • 2013-04-08
  • 2017-03-19
  • 2012-07-25
  • 1970-01-01
  • 2011-02-09
  • 2017-06-02
  • 1970-01-01
  • 2019-06-08
  • 2013-05-31
相关资源
最近更新 更多