Facebook会调整我们上传的图像的大小,如果它高于2 megapixels
。比如我的图片是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;
}
我现在不在任何地方可以测试这个,所以我的纵横比数学可能会被转换。