简体   繁体   中英

Create thumbnail from image

I have this method that receives image and saves it to database:

public void AttachImage(Guid id, Stream imageStream, string imageName)
        {
            Post post = GetPost(id);
            if (post.HasImage())
            {
                _gridFS.Delete(new ObjectId(post.ImageId));
            }

            ObjectId imageId = _gridFS.UploadFromStream(imageName, imageStream);

            post.ImageId = imageId.ToString();

            var filter = Builders<Post>.Filter.Eq(x => x.Id, id);
            var update = Builders<Post>.Update.Set("ImageId", post.ImageId);
            _posts.UpdateOne(filter, update);
        }

And now I don't know how to do the same, but scale it down to thumbnail size. Size should be automatic, I can't just set it to for example 400x400 if image is 1920x1080 .

How to keep aspect ratio and not get down below certain size

first calculate the aspect ratio of the source image, say w/h, or 1920/1080 = 1.77. Then take your target size, say 400x300 and calculate how large the image should be. You can do this based on either the width or height:

  • 300 * 1.77 => 533x300
  • 400 / 1.77 => 400x225

Select one of them, either statically or dynamically depending on if the source aspect ratio is larger than the target aspect ratio. If the resulting dimensions are larger than the target the image will be cropped, if smaller there will be empty areas.

How to scale down image to thumbnail.

Once you know what size the image should have this answer explains how to scale the image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM