使用 PHP 调整图像大小和转换图像

Resize and convert images with PHP

我的以下代码有一些问题。我的任务是开发一个可以上传图像的 PHP 程序,然后将其转换为 jpg 并将其调整为最大宽度 300 像素或高度 300 像素。纵横比应与原始纵横比相同。

最奇怪的是,函数 "convertImage" 输出类似这样的东西:

����JFIF�����'�1�y�^�>�9<���H��^_������|6��a����B�����|%��^#��r�R:,������\z��c����='}U���S�s��$�bO�_��O$"���N74�����tл��ao/�8ԑ�G'�04���'��O�C��7��c1�99#8�׾}y�|�y�������3]ּg��G�t����Q��1x_����v��|8�n��^x�:mγ��[��iQ\>��]*���ĺ��-t{[��d��<-~x[���$���c������q�qӌ���d��=B9�3�<�y�;�I�תx��w�o�����~!|'��������T�7��U����~����ׇ͍5�J��M����,�kcas9�L���Ek[�f��3��랞�=pN2I�`�i���k�i�M��uBc�#���n���@rrFA�>�t�2y�|��c����׾G=r2x��xoW�M�i�5�O:[�yq$�vzu����Q-����Ok��[�Vk��V[���b�.n ��:�g T�*�*IB�)�rv�a��'�)6��vc�e9F��)4����z$��0��?��r8 ��1����3߸9�k�?�}/��oi�Ե�x�h��9��eS��!�����-tD�P��jw�}

最后一个带有 img-tag 的 echo 也没有出现在 html-dom.

HTML:

<form method="POST" enctype="multipart/form-data">
 <table>
  <tr>
   <td>
    <input type="file" id="pic" accept="image/*" name="pic">
   </td>
   <td>
    <input type="submit" id="send" value="Send" name="submit">
   </td>
  </tr
 </table>
</form>

PHP:

<?php
if( isset( $_POST['submit'] ) ) {
 $tmpName = basename($_FILES['pic']['name'];
 $size = getimagesize($tmpName);
 $donePic;
 convertImage($tmpName, $donePic, $size);
 echo '<img src="data:image/jpeg;base64,'.base64_encode($donePic).'"/>'; 
}
?>

函数转换图像

function convertImage($original, $output, $size) {
        //jpg, png, gif, bmp
        $ext = $size['mime'];

        if (preg_match('/jpg|jpeg/i', $ext))
            $imageTemp = imagecreatefromjpeg($original);
        else if (preg_match('/png/i', $ext))
            $imageTemp = imagecreatefrompng($original);
        else if (preg_match('/gif/i', $ext))
            $imageTemp = imagecreatefromgif($original);
        else if (preg_match('/bmp/i', $ext))
            $imageTemp = imagecreatefromwbmp($original);
        else
            return 0;

        $ratio = $size[0]/$size[1]; // width / height
        if ($ratio > 1 ) {
            $width  = 300;
            $heigth = 300 / $ratio;
        } else {
            $width = 300*$ratio;
            $heigth = 300;
        }    

        $resizedImg = imagecreatetruecolor($width, $heigth);
        imagecopyresampled($resizedImg, $imageTemp, 0,0,0,0,$width, $heigth, $size[0], $size[1]);
        imagedestroy($imageTemp);

        imagejpeg($resizedImg, $output);
        imagedestroy($resizedImg);

        return 1;
    }

如果您需要任何其他信息,请随时问我。

谢谢大家!

请参阅下方 link 以了解 PHP 中的图像调整大小。

https://code.tutsplus.com/tutorials/image-resizing-made-easy-with-php--net-10362

我在 Kaddath 的帮助下解决了我的问题。谢谢!

我不得不更改代码

imagedestroy($imageTemp);
imagejpeg($resizedImg, $output);
imagedestroy($resizedImg);

imagedestroy($imageTemp);

//starting an output buffer to get the data
ob_start();

imagejpeg($resizedImg);

//here we get the data
$output = ob_get_clean();

imagedestroy($resizedImg);

您计算新图像比率的公式有误。这是固定的:

if ($ratio > 1 ) {
    $width  = 300 * $ratio;
    $heigth = 300;
} else {
    $width = 300;
    $heigth = 300 / $ratio;
}