我在pngtojpgAction()
下的控制器中有以下代码,我使用ajax调用它。
通过这个
$this->getRequest()->getParam('imagedata'));
声明我得到的格式如data:image/jpeg;base64,/9j/4AAQSkZJR......AH9T796KtUV1HGf/Z
这是一个png图像数据。
现在我使用以下代码将此png图像转换为jpeg并将dpi增加到300.
public function pngtojpgAction()
{
//Code to convert png to jpg image
$input = imagecreatefrompng($this->getRequest()->getParam('imagedata'));
$width=imagesx($input);
$height=imagesy($input);
$output = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($output, 255, 255, 255);
imagefilledrectangle($output, 0, 0, $width, $height, $white);
imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
ob_start();
imagejpeg($output);
$contents = ob_get_contents();
ob_end_clean();
//echo 'data:image/jpeg;base64,'.base64_encode($contents); /*Up to here code works well*/
$jpgImage='data:image/jpeg;base64,'.base64_encode($contents);
$image = file_get_contents($jpgImage);
$image = substr_replace($image, pack("cnn", 1, 300, 300), 13, 5);
header("Content-type: image/jpeg");
header('Content-Disposition: attachment; filename="'.basename($jpgImage).'"');
echo $image;
}
使用此
$image = substr_replace($image, pack("cnn", 1, 300, 300), 13, 5);
我想将图像的dpi提高到300 dpi。
我无法使用这些代码行更改图像dpi
$jpgImage='data:image/jpeg;base64,'.base64_encode($contents);
$image = file_get_contents($jpgImage);
$image = substr_replace($image, pack("cnn", 1, 300, 300), 13, 5);
header("Content-type: image/jpeg");
header('Content-Disposition: attachment; filename="'.basename($jpgImage).'"');
echo $image;
我使用此链接作为参考Change image dpi using php
答案 0 :(得分:4)
经过一些改动后,它对我有用。
public function pngtojpgAction()
{
//Code to convert png to jpg image
$input = imagecreatefrompng($this->getRequest()->getParam('imagedata'));
$width=imagesx($input);
$height=imagesy($input);
$output = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($output, 255, 255, 255);
imagefilledrectangle($output, 0, 0, $width, $height, $white);
imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
ob_start();
imagejpeg($output);
$contents = ob_get_contents();
//Converting Image DPI to 300DPI
$contents = substr_replace($contents, pack("cnn", 1, 300, 300), 13, 5);
ob_end_clean();
echo 'data:image/jpeg;base64,'.base64_encode($contents);
}
答案 1 :(得分:3)
我会改用imagemagick:
convert Bird.jpg -density 300 Bird2.jpg
但你也可以用GD做到这一点。
$filename = 'Bird.jpg';
$source = imagecreatefromjpeg($filename);
list($width, $height) = getimagesize($filename);
$b = new Resampler;
$im = $b->resample($source, $height, $width, 300);
file_put_contents('Bird2.jpg', $im);
在Windows环境中测试。
答案 2 :(得分:0)
简单代码即可重新生成质量可调的图像。
function compress_image($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
$image = imagecreatefromjpeg($source_url);
imagejpeg($image, $destination_url, $quality);
return $destination_url;
}
echo compress_image($_FILES["file"]["tmp_name"], "destination .jpg", 80);//Adjust Quality
注意:确保已安装PHP的GD库。