I have some problems with my following code. I've got a task to develop a PHP program that can upload an image, then convert it to jpg and resize it to max width 300px or height 300px. The aspect ratio should be the same as the original one.
The strangest thing is, that the function "convertImage" output something like that:
����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�}
Also the last echo with the img-tag doesn't appear in the 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
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;
}
If you need any other information, feel free to ask me.
Thanks everyone!
I solved my problem with the help of Kaddath. Thanks!
I had to change the code from
imagedestroy($imageTemp);
imagejpeg($resizedImg, $output);
imagedestroy($resizedImg);
to
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);