【问题标题】:Reduce image size while uploading [duplicate]上传时减小图像大小[重复]
【发布时间】:2012-08-28 15:01:38
【问题描述】:

上传时是否可以缩小图片尺寸?

大小可以从 2MB 减少到 500kb 或更少或类似的东西 上传文件时?

【问题讨论】:

  • 您在说什么类型的图像(PNG、JPG、BMP 等)?您对哪种语言感兴趣?您已经用 3 种不同的可能性标记了您的问题...
  • 如果您使用的是 Java,肯定有一些库可以帮助您在上传之前减小图像的大小。如果您使用的是 PHP,有几个(Imagick、GD、Exactimage 等)可以在上传完成后为您提供帮助。但是,您不能在期间上传。
  • 是否可以使用任何语言.. 我更喜欢 php 并且在上传到服务器时...这样小尺寸的图像会进入服务器占用更少的服务器空间...谢谢

标签: java php javascript


【解决方案1】:

当然,它工作正常。我在 PHP 中使用这个类:

<?php

    function thumbnail( $img, $source, $dest, $maxw, $maxh ) {      
        $jpg = $source.$img;

        if( $jpg ) {
            list( $width, $height  ) = getimagesize( $jpg ); //$type will return the type of the image
            $source = imagecreatefromjpeg( $jpg );

            if( $maxw >= $width && $maxh >= $height ) {
                $ratio = 1;
            }elseif( $width > $height ) {
                $ratio = $maxw / $width;
            }else {
                $ratio = $maxh / $height;
            }

            $thumb_width = round( $width * $ratio ); //get the smaller value from cal # floor()
            $thumb_height = round( $height * $ratio );

            $thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
            imagecopyresampled( $thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height );

            $path = $dest.$img."_thumb.jpg";
            imagejpeg( $thumb, $path, 75 );
        }
        imagedestroy( $thumb );
        imagedestroy( $source );
    }

?>

imagejpeg( $thumb, $path, 75 ); 是上传后你想要的图片大小和质量。

在 PHP 脚本中调用:

if( isset( $_FILES['img-content'] ) ) {
    $img = str_replace( " ","_",$_FILES['img-content']['name'] );
    move_uploaded_file( $_FILES['img-content']['tmp_name'], "../../images/content/".$img );
    $source = "../../images/content/";
    $dest = "../../images/thumb/";
    thumbnail( $img, $source, $dest, 480, 400 );

}

【讨论】:

  • thx 但这会在上传后减小边...并且输出的大小会减小但是在服务器上会有一个 4 mb 或 2 mb 的大文件...我们可以减小大小上传时? ...所以我可以为每张图片 500 kb 的用户设置上传限制,让他们上传任何大小,脚本会减小大小??
  • 上传后删除旧图并保留缩略图如何?希望它符合您的需求
  • 谢谢帮助...但我希望用户上传个人资料照片...所以我无法删除所有图片...谢谢
  • 任何方式我都会尝试这个脚本...你能解释一下 $img, $source, $dest, $maxw, $maxh ... 据我所知 $img(?), $source(是图片的来源), newname, $maxwidth, $maxhight
  • 查看上面的答案,我通过脚本调用了这个函数。希望你能弄清楚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-14
  • 2012-01-10
  • 1970-01-01
  • 2017-01-10
  • 2013-10-01
  • 2018-11-05
  • 1970-01-01
相关资源
最近更新 更多