如何用PHP创建JPEG视网膜图像

时间:2013-05-17 12:56:58

标签: php png jpeg retina

几个月前,我写了以下脚本,用PHP to Retinanon视网膜图像转换上传的图像。使用此脚本的iphone应用程序仅使用PNG图像,因此我编写了使用PNG的脚本。

$filename = dirname(__FILE__)."/uploads/" . $_FILES['myFile']['name'];
$filename = str_replace('.png', '_retina.png', $filename);
file_put_contents($filename, file_get_contents($_FILES['myFile']['tmp_name']));

$image_info = getimagesize($filename);
$image = imagecreatefrompng($filename);

$width = imagesx($image);
$height = imagesy($image);

$new_width = $width/2.0;
$new_height = $height/2.0;

$new_image = imagecreatetruecolor($new_width, $new_height);

imagealphablending($new_image, false);
imagesavealpha($new_image, true);
$color = imagecolortransparent($new_image, imagecolorallocatealpha($new_image, 0, 0, 0, 127));
imagefill($new_image, 0, 0, $color);

imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

$new_filename = str_replace('_retina.png', '.png', $filename);

imagepng($new_image, $new_filename);

现在我需要相同的脚本,然后与Jpeg图像一起使用。因为iphone应用程序将加载更高分辨率的图像,所以我们选择了Jpeg。但我无法弄清楚如何做到这一点。

到目前为止我尝试了什么:

  • 用jpeg版本替换imagecreatefrompng
  • 用jpeg版本替换imagepng

是否有人有一个可以让我找到正确方向的工作示例或有用的链接?

1 个答案:

答案 0 :(得分:1)

我弄清楚问题是关于什么的。我假设jpg php函数无法处理透明度,所以我删除了那些行并忘了它们。显然它只是创建一个白色背景,它不会失败。所以脚本如下:

$filename = dirname(__FILE__)."/uploads/" . $_FILES['myFile']['name'];
$filename = str_replace('.jpg', '_retina.jpg', $filename);
file_put_contents($filename, file_get_contents($_FILES['myFile']['tmp_name']));

$image_info = getimagesize($filename);
$image = imagecreatefromjpeg($filename);

$width = imagesx($image);
$height = imagesy($image);

$new_width = $width/2.0;
$new_height = $height/2.0;

$new_image = imagecreatetruecolor($new_width, $new_height);

imagealphablending($new_image, false);
imagesavealpha($new_image, true);
$color = imagecolortransparent($new_image, imagecolorallocatealpha($new_image, 0, 0, 0, 127));
imagefill($new_image, 0, 0, $color);

imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

$new_filename = str_replace('_retina.jpg', '.jpg', $filename);

imagejpeg($new_image, $new_filename);