Create Thumbnail Image

Create thumbnail image

You have to use GetThumbnailImage method in the Image class:

https://msdn.microsoft.com/en-us/library/8t23aykb%28v=vs.110%29.aspx

Here's a rough example that takes an image file and makes a thumbnail image from it, then saves it back to disk.

Image image = Image.FromFile(fileName);
Image thumb = image.GetThumbnailImage(120, 120, ()=>false, IntPtr.Zero);
thumb.Save(Path.ChangeExtension(fileName, "thumb"));

It is in the System.Drawing namespace (in System.Drawing.dll).

Behavior:

If the Image contains an embedded thumbnail image, this method
retrieves the embedded thumbnail and scales it to the requested size.
If the Image does not contain an embedded thumbnail image, this method
creates a thumbnail image by scaling the main image.


Important: the remarks section of the Microsoft link above warns of certain potential problems:

The GetThumbnailImage method works well when the requested thumbnail
image has a size of about 120 x 120 pixels. If you request a large
thumbnail image (for example, 300 x 300) from an Image that has an
embedded thumbnail, there could be a noticeable loss of quality in the
thumbnail image
.

It might be better to scale the main image (instead
of scaling the embedded thumbnail) by calling the DrawImage method.

How to create thumbnail image in .net core? Using the help of IFormFile

Finally got the answer

Installed System.Drawing.Common -Version 4.5.1 package

Open the package manager and run the below code for installing the package

Install-Package System.Drawing.Common -Version 5.0.2

Then use the below code:

using System.Drawing;

var stream = ProductImage.OpenReadStream();

var newImage = GetReducedImage(32,32,stream);
newImage.Save("path+filename");

public Image GetReducedImage(int width, int height, Stream resourceImage)
{
try
{
var image = Image.FromStream(resourceImage);
var thumb = image.GetThumbnailImage(width, height, () => false, IntPtr.Zero);

return thumb;
}
catch (Exception e)
{
return null;
}
}

Creating a thumbnail from an uploaded image

UPDATE:

If you want to take advantage of Imagick (if it is installed on your server). Note: I didn't use Imagick's nature writeFile because I was having issues with it on my server. File put contents works just as well.

<?php
/**
*
* Generate Thumbnail using Imagick class
*
* @param string $img
* @param string $width
* @param string $height
* @param int $quality
* @return boolean on true
* @throws Exception
* @throws ImagickException
*/
function generateThumbnail($img, $width, $height, $quality = 90)
{
if (is_file($img)) {
$imagick = new Imagick(realpath($img));
$imagick->setImageFormat('jpeg');
$imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
$imagick->setImageCompressionQuality($quality);
$imagick->thumbnailImage($width, $height, false, false);
$filename_no_ext = reset(explode('.', $img));
if (file_put_contents($filename_no_ext . '_thumb' . '.jpg', $imagick) === false) {
throw new Exception("Could not put contents.");
}
return true;
}
else {
throw new Exception("No valid image provided with {$img}.");
}
}

// example usage
try {
generateThumbnail('test.jpg', 100, 50, 65);
}
catch (ImagickException $e) {
echo $e->getMessage();
}
catch (Exception $e) {
echo $e->getMessage();
}
?>

I have been using this, just execute the function after you store the original image and use that location to create the thumbnail. Edit it to your liking...

function makeThumbnails($updir, $img, $id)
{
$thumbnail_width = 134;
$thumbnail_height = 189;
$thumb_beforeword = "thumb";
$arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($arr_image_details[2] == IMAGETYPE_GIF) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == IMAGETYPE_JPEG) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == IMAGETYPE_PNG) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom("$updir" . $id . '_' . "$img");
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img");
}
}

The above function creates images with a uniform thumbnail size. If the image doesn't have the same dimensions as the specified thumbnail size (proportionally), it just has blackspace on the top and bottom.

Create thumbnail images for jpegs with python

See: http://www.pythonware.com/products/pil/index.htm

import os, sys
import Image

size = 128, 128

for infile in sys.argv[1:]:
outfile = os.path.splitext(infile)[0] + ".thumbnail"
if infile != outfile:
try:
im = Image.open(infile)
im.thumbnail(size)
im.save(outfile, "JPEG")
except IOError:
print "cannot create thumbnail for", infile

How to create a thumbnail image in NodeJs using sharp library?

If you give both width and height, sharp will usually need to either add or remove pixels on one axis. You can control what it does with the fit parameter:

http://sharp.pixelplumbing.com/en/stable/api-resize/

The default is centre, it sounds like you'd prefer outside.

How to generate a thumbnail image after adding an image inside an input type=file in a form and submitting them both on the same form

I found This simpler yet powerful tutorial. It simply creates an img element and, using the fileReader object, assigns its source attribute as the value of the form input

function previewFile() {  var preview = document.querySelector('img');  var file    = document.querySelector('input[type=file]').files[0];  var reader  = new FileReader();
reader.onloadend = function () { preview.src = reader.result; }
if (file) { reader.readAsDataURL(file); } else { preview.src = ""; }}
<input type="file" onchange="previewFile()"><br><img src="" height="200" alt="Image preview...">

What is the best way for creating thumbnail from an existing image

The answers to this question may be highly opinionated, but here are my two cents.

In general, you should go for separate thumbnails that are generated during upload of images or, which is way better, in the background after uploading an image. With Laravels queue system, this is pretty straight forward. The reasons are very simple and already mentioned in the comments:

  • Thumbnails only need to be generated once (generating thumbnails on a per-request basis causes heavy workload and a potential performance issue)
  • Storage is cheap and fast

Identication of thumnails can either be done by storing the filename of the thumbnail or, as you already suggested, by using some logic to resolve thumbnails based on the original file. Personally, I would use a folder structure that allows you to generate a wide variety of different thumbnails, e.g.:

 images/
original/
123456789.jpg
thumbnail/
100x100/
123456789.jpg
200x200/
123456789.jpg

The directory names 100x100 and 200x200 can of course be changed to something that suits you. Using the suggested ones would mean to me that a thumbnail is not wider than 100px and not higher than 100px either. It doesn't mean every thumbnail is exactly 100x100 pixels, although you can also implement such a thumbnail generator if you need.

Be careful that you might need some fallback logic to display thumbnails while they are still being generated if you utilize the background workers for this. A fallback could be a default image or the original resized via HTML.


By the way, if you implement a thumbnail generator, you can consider implementing an image optimizer as well. Most images can be minified without users noticing a (significant) difference. Whether such a system is worth it or not, depends on the amount of images you display and how much traffic there is on your site. For heavily used websites, this may be a good idea to save some traffic. An existing solution for this is spatie/image-optimizer (I'm not associated with spatie in any way).



Related Topics



Leave a reply



Submit