Creating a Thumbnail from an Uploaded Image

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.

Angular - Generate thumbnails for uploaded image/video

You can try to create a video element and set your video to it. After loading the video inside the element a canvas can be used to extract an image from that video.
This might be useful https://stackoverflow.com/a/63474748/10143503

Create Thumbnails for Uploaded Images

The answer is this:

var path2 = string.Format("{0}\\{1}", pathString2, file.FileName)

WebImage img = new WebImage(file.InputStream);
img.Resize(250, 250);
img.Save(path2);

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

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...">

generate thumbnail when image uploaded django

As said in the comment, you can work with base64 encoded image instead. In order to do this, first change the thumbnail field to the following:

thumbnail = models.CharField(max_length=2000, blank=True, null=True)

Then, override the model save method and add the following code:

def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
if not self.image:
self.thumbnail = None
else:
thumbnail_size = 50, 50
data_img = BytesIO()
tiny_img = Image.open(self.image)
tiny_img.thumbnail(thumbnail_size)
tiny_img.save(data_img, format="BMP")
tiny_img.close()
try:
self.thumbnail = "data:image/jpg;base64,{}".format(
base64.b64encode(data_img.getvalue()).decode("utf-8")
)
except UnicodeDecodeError:
self.blurred_image = None

super(Image, self).save(force_insert, force_update, using, update_fields)

You can change the thumbnail_size variable to match your needs.
Lastly, add the following to your import section:

import base64
from io import BytesIO

Don't forget to run makemigrations and migrate commands! Let me know if you have any problems.

Upload an image and create its thumbnail Laravel 5.2

For anyone wonder how to fix this or do something similar, I just found the solution:

if($file = $request->hasFile('image')) {
$file = $request->file('image');
$extension = $file->getClientOriginalName();
$username = Auth::user()->username;
$thumb = Image::make($file->getRealPath())->resize(100, 100, function ($constraint) {
$constraint->aspectRatio(); //maintain image ratio
});
$destinationPath = public_path('/uploads/products/' . $username);
$file->move($destinationPath, $extension);
$thumb->save($destinationPath.'/thumb_'.$extension);
$product['imagePath'] = '/uploads/products/'. $username . '/' . $extension;
$product['thumbnail'] = '/uploads/products/'. $username . '/thumb_' . $extension;
}

So this piece of code makes a dynamic folder (I chose the username of the authenticated user) inside /uploads/products/. In that folder it uploads the picture and also creates a resized one, for thumbnail use. Also, when it creates the thumbnail, it holds the ratio of the original picture so it doesn't lose proportions

Thumbnail creation of uploaded image

I have an alternative way of creating thumbnails from image while upload which is as follows :

Add the following directives in your using namespace :

using System.Drawing;
using System.Drawing.Imaging;

Add the following code in your controller action for creating thumbnails

using (var image = Image.FromStream(file.InputStream, true, true)) /* Creates Image from specified data stream */
{
using (var thumb = image.GetThumbnailImage(
36, /* width*/
30, /* height*/
() => false,
IntPtr.Zero))
{
var jpgInfo = ImageCodecInfo.GetImageEncoders().Where(codecInfo => codecInfo.MimeType == "image/png").First(); /* Returns array of image encoder objects built into GDI+ */
using (var encParams = new EncoderParameters(1))
{
var appDataThumbnailPath = Server.MapPath("~/Uploads/Thumbnail/" + User.id);
if (!Directory.Exists(appDataThumbnailPath))
{
Directory.CreateDirectory(appDataThumbnailPath);
}
string outputPath = Path.Combine(appDataThumbnailPath, fileName);
long quality = 100;
encParams.Param[0] = new EncoderParameter(Encoder.Quality, quality);
thumb.Save(outputPath, jpgInfo, encParams);
}
}
}

Here the file is HttpPostedFileBase object which has the input image , outputPath is the destination file for thumbnail. By the following process you will have your thumbnails.

How to create thumbnail for uploaded images on DropZone.js?

You should use createThumbnailFromUrl , orginally posted here

myDropzone.emit("addedfile", mockFile);
myDropzone.createThumbnailFromUrl(mockFile, '/your-image.jpg');


Related Topics



Leave a reply



Submit