javascript - Facebook 风格上传的图像调整大小和压缩

标签 javascript c# php jquery asp.net-mvc

如果上传的图像大小不超过2 兆像素,Facebook 会调整其大小。比如我的图片是3264x1832,facebook调整大小为2048x1529它。那么,如果哪条边长,图像就会缩小到该边2048px。测量另一个边缘正在减少的减少量。之后图像压缩后图像尺寸更小。该方法在大图像中要小心。我将在我的 mvc 5 项目中使用该方法,如何找到像该方法这样的 c#、jquery、javascrip、php 插件或 api?

最佳答案

这需要在您的 php 服务器上安装 GD,并期望 path/to/temp/image.jpg 是上传图像的位置。您可能需要使用 try/catch 以防上传不受支持的文件类型或损坏的图像。

主要程序代码如下:

$maxWidth = 2048;
$maxHeight = 2048;
$compression = 75;

//Create an image object out of the uploaded file
$sourceImage = imagecreatefromjpeg('path/to/temp/image.jpg'); 

//Resize the image
$resizedImage = ImageSizeDown($sourceImage, $maxWidth, $maxHeight);

//Save the image as a jpeg to it's new home
imagejpeg($resizedImage, 'path/to/permanent/image.jpg', $compression);

这些是额外的必要功能:

//Function for resizing an image if it's larger than a certain resolution
function ImageSizeDown($image, $maxWidth, $maxHeight) {
    $maxAspect = $maxWidth / $maxHeight;
    $sourceWidth = imagesx($image);
    $sourceHeight = imagesy($image);
    $sourceAspect = $sourceWidth / $sourceHeight;
    if($sourceWidth > $maxWidth || $sourceHeight > $maxHeight) {
        if($maxAspect > $sourceAspect) {
            $newWidth = (int)$maxWidth;
            $newHeight = (int)($maxWidth / $sourceWidth * $sourceHeight);
        }
        else { 
            $newHeight = (int)$maxHeight;
            $newWidth = (int)($maxHeight / $sourceHeight * $sourceWidth);
        }
        $result = TransparentImage($newWidth, $newHeight);
        imagesavealpha($image, true);
        imagealphablending($image, false);
        imagecopyresampled($result, $image, 0, 0, 0, 0, $newWidth, $newHeight, $sourceWidth, $sourceHeight);
        return $result;
    }
    else return $image; //Image is already small enough
}

//Handy function for creating a base for most any image stuff, especially PNG
function TransparentImage($x, $y) { 
    $image = imagecreatetruecolor($x, $y);
    imagesavealpha($image, true);
    imagealphablending($image, false);
    $transparent = imagecolorallocatealpha($image, 200, 200, 200, 127);
    imagefill($image, 0, 0, $transparent);
    return $image;
}

目前我无法在任何地方对此进行测试,因此我的长宽比数学可能会被调换。

关于javascript - Facebook 风格上传的图像调整大小和压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28336017/

相关文章:

javascript - 测量 javascript 中多个 ajax 请求的带宽消耗

javascript - 如何禁用 php 中的日期数组

javascript - 为什么 IE 中的 Magento js/varien/form.js 错误 - js fiddle

c# - 如何用我自己在 asp.net core 中的实现替换默认的 IControllerFactory?

c# - C#中如何去掉String的最后一个字符?

c# - 同类的 Fluent/NHibernate Collections

php - laravel - 登录重定向丢失了 url 哈希

javascript - 自动进度条

javascript - 如何在c++中使用html、javascript

javascript - 如何创建仅包含街道名称的空谷歌地图