<p>I want to allow users to upload avatar-type images in a variety of formats (<strong>GIF, JPEG, and PNG at least</strong>), but to save them all as <strong>PNG database BLOBs</strong>. If the images are oversized, pixelwise, I want to resize them before DB-insertion.</p>

<p><strong>What is the best way to use GD to do the resizing and PNG conversion?</strong></p>

<p>Edit: Sadly, only <a href="http://php.net/manual/en/book.image.php" rel="nofollow noreferrer">GD</a> is available on the server I need to use, no  <a href="http://www.imagemagick.org/script/index.php" rel="nofollow noreferrer">ImageMagick</a>.</p>

[{'answer_id': 22267, 'author': 'tslocum', 'author_id': 1662, 'author_profile': 'https://Stackoverflow.com/users/1662', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://www.phpit.net/article/image-manipulation-php-gd-part2/" rel="nofollow noreferrer">This article</a> seems like it would fit what you want.  You\'ll need to change the saving imagejpeg() function to imagepng() and have it save the file to a string rather than output it to the page, but other than that it should be easy copy/paste into your existing code.</p>\n'}, {'answer_id': 22270, 'author': 'ceejayoz', 'author_id': 1902010, 'author_profile': 'https://Stackoverflow.com/users/1902010', 'pm_score': 1, 'selected': False, 'text': '<p>Is GD absolutely required? <a href="http://imagemagick.org/" rel="nofollow noreferrer">ImageMagick</a> is faster, generates better images, is more configurable, and finally is (IMO) much easier to code for.</p>\n'}, {'answer_id': 22271, 'author': 'Espo', 'author_id': 2257, 'author_profile': 'https://Stackoverflow.com/users/2257', 'pm_score': 0, 'selected': False, 'text': '<p>I think <a href="http://codecaine.co.za/posts/zend-image-class-to-convert-and-resize-images" rel="nofollow noreferrer">this page</a> is a good starting point. It uses imagecreatefrom(jpeg/gif/png) and resize and converts the image and then outputs to the browser. Instead of outputting the browser you could output to a BLOB in a DB without many minuttes of code-rewrite.</p>\n'}, {'answer_id': 22282, 'author': 'rix0rrr', 'author_id': 2474, 'author_profile': 'https://Stackoverflow.com/users/2474', 'pm_score': 2, 'selected': False, 'text': "<p>If you want to use gdlib, use gdlib 2 or higher. It has a function called imagecopyresampled(), which will interpolate pixels while resizing and look much better.</p>\n\n<p>Also, I've always heard noted around the net that storing images in the database is bad form:</p>\n\n<ul>\n<li>It's slower to access than the disk</li>\n<li>Your server will need to run a script to get to the image instead\nof simply serving a file</li>\n<li>Your script now is responsible for a lot of stuff the web server used\nto handle:\n\n<ul>\n<li>Setting the proper Content-Type header</li>\n<li>Setting the proper caching/timeout/E-tag headers, so clients can properly cache the image. If do not do this properly, the image serving script will be hit on every request, increasing the load on the server even more.</li>\n</ul></li>\n</ul>\n\n<p>The only advantage I can see is that you don't need to keep your database and image files synchronized. I would still recommend against it though.</p>\n"}, {'answer_id': 22300, 'author': 'Ross', 'author_id': 2025, 'author_profile': 'https://Stackoverflow.com/users/2025', 'pm_score': 3, 'selected': False, 'text': '<p>Your process steps should look like this:</p>\n\n<ol>\n<li><a href="http://www.php.net/manual/en/function.exif-imagetype.php" rel="nofollow noreferrer">Verify</a> the <a href="http://www.php.net/manual/en/function.imagetypes.php" rel="nofollow noreferrer">filetype</a></li>\n<li>Load the image if it is a supported filetype into GD using <a href="http://www.php.net/manual/en/function.imagecreatefromjpeg.php" rel="nofollow noreferrer">imagecreatefrom*</a></li>\n<li>Resizing using <a href="http://www.php.net/manual/en/function.imagecopyresized.php" rel="nofollow noreferrer">imagecopyresize</a> or <a href="http://www.php.net/manual/en/function.imagecopyresampled.php" rel="nofollow noreferrer">imagecopyresampled</a></li>\n<li>Save the image using <a href="http://www.php.net/manual/en/function.imagepng.php" rel="nofollow noreferrer">imagepng($handle, \'filename.png\', $quality, $filters)</a></li>\n</ol>\n\n<blockquote>\n  <p>ImageMagick is faster, generates better images, is more configurable, and finally is (IMO) much easier to code for.</p>\n</blockquote>\n\n<p>@ceejayoz Just wait for the new GD - it\'s OOP like MySQLi and it\'s actually not bad :)</p>\n'}, {'answer_id': 22324, 'author': 'Grzegorz Gierlik', 'author_id': 1483, 'author_profile': 'https://Stackoverflow.com/users/1483', 'pm_score': 2, 'selected': False, 'text': '<p>Are you sure you have no ImageMagick on server?</p>\n\n<p>I guest you use PHP (question is tagged with PHP). Hosting company which I use has no ImageMagick extension turned on according to phpinfo().</p>\n\n<p>But when I asked them about they said <em>here is the list of ImageMagick programs available from PHP code</em>. So simply -- there are no IM interface in PHP, but I can call IM programs directly from PHP.</p>\n\n<p>I hope you have the same option.</p>\n\n<p>And I <strong>strongly</strong> agree -- storing images in database is not good idea.</p>\n'}, {'answer_id': 22333, 'author': 'Andy', 'author_id': 1993, 'author_profile': 'https://Stackoverflow.com/users/1993', 'pm_score': 2, 'selected': False, 'text': '<p>Something like this, perhaps: </p>\n\n<pre><code>\n&lt;?php\n   //Input file\n   $file = "myImage.png";\n   $img = ImageCreateFromPNG($file);\n\n   //Dimensions\n   $width = imagesx($img);\n   $height = imagesy($img);\n   $max_width = 300;\n   $max_height = 300;\n   $percentage = 1;\n\n   //Image scaling calculations\n   if ( $width > $max_width ) { \n      $percentage = ($height / ($width / $max_width)) > $max_height ?\n           $height / $max_height :\n           $width / $max_width;\n   }\n   elseif ( $height > $max_height) {\n      $percentage = ($width / ($height / $max_height)) > $max_width ? \n           $width / $max_width :\n           $height / $max_height;\n   }\n   $new_width = $width / $percentage;\n   $new_height = $height / $percentage;\n\n   //scaled image\n   $out = imagecreatetruecolor($new_width, $new_height);\n   imagecopyresampled($out, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);\n\n   //output image\n   imagepng($out);\n?&gt;\n</code></pre>\n\n<p>I haven\'t tested the code so there might be some syntax errors, however it should give you a fair presentation on how it could be done. Also, I assumed a PNG file. You might want to have some kind of switch statement to determine the file type.</p>\n'}, {'answer_id': 22403, 'author': 'Acuminate', 'author_id': 2482, 'author_profile': 'https://Stackoverflow.com/users/2482', 'pm_score': 6, 'selected': True, 'text': "<pre><code>&lt;?php                                              \n/*\nResizes an image and converts it to PNG returning the PNG data as a string\n*/\nfunction imageToPng($srcFile, $maxSize = 100) {  \n    list($width_orig, $height_orig, $type) = getimagesize($srcFile);        \n\n    // Get the aspect ratio\n    $ratio_orig = $width_orig / $height_orig;\n\n    $width  = $maxSize; \n    $height = $maxSize;\n\n    // resize to height (orig is portrait) \n    if ($ratio_orig &lt; 1) {\n        $width = $height * $ratio_orig;\n    } \n    // resize to width (orig is landscape)\n    else {\n        $height = $width / $ratio_orig;\n    }\n\n    // Temporarily increase the memory limit to allow for larger images\n    ini_set('memory_limit', '32M'); \n\n    switch ($type) \n    {\n        case IMAGETYPE_GIF: \n            $image = imagecreatefromgif($srcFile); \n            break;   \n        case IMAGETYPE_JPEG:  \n            $image = imagecreatefromjpeg($srcFile); \n            break;   \n        case IMAGETYPE_PNG:  \n            $image = imagecreatefrompng($srcFile);\n            break; \n        default:\n            throw new Exception('Unrecognized image type ' . $type);\n    }\n\n    // create a new blank image\n    $newImage = imagecreatetruecolor($width, $height);\n\n    // Copy the old image to the new image\n    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);\n\n    // Output to a temp file\n    $destFile = tempnam();\n    imagepng($newImage, $destFile);  \n\n    // Free memory                           \n    imagedestroy($newImage);\n\n    if ( is_file($destFile) ) {\n        $f = fopen($destFile, 'rb');   \n        $data = fread($f);       \n        fclose($f);\n\n        // Remove the tempfile\n        unlink($destFile);    \n        return $data;\n    }\n\n    throw new Exception('Image conversion failed.');\n}\n</code></pre>\n"}, {'answer_id': 43836, 'author': 'Cheekysoft', 'author_id': 1820, 'author_profile': 'https://Stackoverflow.com/users/1820', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://phpthumb.sourceforge.net/" rel="nofollow noreferrer">phpThumb</a> is a high-level abstraction that may be worth looking at.</p>\n'}]
['https://Stackoverflow.com/questions/22259', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1820/']