如何使用php将图像更改为jpg并将dpi设置为300?

Muk*_*esh 2 php gd magento

我在控制器中有以下代码,pngtojpgAction()我在该控制器下使用 ajax 进行调用。

通过这个

$this->getRequest()->getParam('imagedata'));
Run Code Online (Sandbox Code Playgroud)

声明我得到这样的模式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;
    
}
Run Code Online (Sandbox Code Playgroud)

使用这个

 $image = substr_replace($image, pack("cnn", 1, 300, 300), 13, 5);
Run Code Online (Sandbox Code Playgroud)

我想将图像的 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;
Run Code Online (Sandbox Code Playgroud)

我使用此链接作为参考Change image dpi using php

Muk*_*esh 5

进行一些更改后,它对我有用。

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); 

}
Run Code Online (Sandbox Code Playgroud)