0

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 change image size](https://stackoverflow.com/questions/1922040/how-to-resize-an-image-c-sharp) might be relevant. – JonasH May 17 '21 at 10:52
  • @JonasH they want to scale it down to preset width and height. I can technically just take original size and divide it by something, but maybe there is more automatic way. –  May 17 '21 at 10:56
  • What does `automatic` mean? – mjwills May 17 '21 at 10:58
  • Is that the core of the question? How to determine what size the thumbnail should have? In that case, what requirements do you have? keep aspect ratio? clip image or leave empty space? – JonasH May 17 '21 at 11:00
  • https://www.nuget.org/packages/ImageLibrary/ – mjwills May 17 '21 at 11:00
  • @JonasH question is; 1. How to scale down image to thumbnail. If there is no automatic way 2. How to keep aspect ratio and not get down below certain size. Scaling down FHD image 4 times down will create some sort of thumbnail, but scaling 500x500 image 4 times down will create very tiny image. –  May 17 '21 at 11:21

1 Answers1

0

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.

JonasH
  • 28,608
  • 2
  • 10
  • 23