仅使用图像字节数组确定尺寸信息和裁剪


Determining dimension information and cropping using only an Image Byte Array

我设置了一个API来接收(除其他外)来自移动应用程序的图像字节数组。一旦接收到,图像将流式传输到Amazon S3并保存为png。一切都很好,但是我有一个问题,一些收到的图像是不同的尺寸。

是否有可能确定图像的宽度和高度仅使用字节数组(即,不保存它作为一个图像到服务器第一),如果有必要裁剪图像?

好的,最后我算出来了,它是这样的:

// First get the data and decode    
$image_data = base64_decode($image_data);
$image_created = imagecreatefromstring($image_data);
$image_width = imagesx($image_created);
$image_height = imagesy($image_created);
$image_aspect_ratio = $image_width / $image_height;
$desired_aspect_ratio = 512 / 512;
// Check if we need to resize
if($image_aspect_ratio > $desired_aspect_ratio) {
    $manipulate_image = true;
    $temp_height = 512;
    $temp_width = ( int ) (512 * $image_aspect_ratio);
} else if($image_aspect_ratio < $desired_aspect_ratio) {
    $manipulate_image = true;
    $temp_width = 512;
    $temp_height = ( int ) (512 / $image_aspect_ratio);
} else {
    $manipulate_image = false;
}
// Resize if neccesary
if($manipulate_image){
    $temp_gdim = imagecreatetruecolor($temp_width, $temp_height);
    $x0 = ($temp_width - 512) / 2;
    $y0 = ($temp_height - 512) / 2;
    imagecopyresampled($temp_gdim, $image_created, 0, 0, 0, 0, $temp_width, $temp_height, $image_width, $image_height);
    $desired_gdim = imagecreatetruecolor(512, 512);
    imagecopy($desired_gdim, $temp_gdim, 0, 0, $x0, $y0, 512, 512);
    // Now get the string back
    ob_start();
    imagepng($desired_gdim);
    $image_data =  ob_get_contents();
    ob_end_clean();
    imagedestroy($image_created);
    imagedestroy($desired_gdim);            
}

我在这里找到了它的一般要点:http://salman-w.blogspot.co.uk/2009/04/crop-to-fit-image-using-aspphp.html