Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.Drawing.Imaging;
- using System.IO;
- namespace Core.Drawing {
- public class ImageResizer {
- public static void ResizeImage(string originalFile,string newFile,Size size,bool resizeExactly = false) {
- ResizeImage(originalFile,newFile,size.Width,size.Height,resizeExactly: resizeExactly,onlyResizeIfWider:false);
- }
- public static void ResizeImage(string originalFile,string newFile,int newWidth,int maxHeight,bool resizeExactly, bool onlyResizeIfWider = false) {
- using(Image fullsizeImage = Image.FromFile(originalFile)) {
- // Prevent using images internal thumbnail
- fullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
- fullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
- int newHeight = maxHeight;
- if(resizeExactly == false) {
- if(onlyResizeIfWider) {
- if(fullsizeImage.Width <= newWidth) {
- newWidth = fullsizeImage.Width;
- }
- }
- newHeight = fullsizeImage.Height * newWidth / fullsizeImage.Width;
- if(newHeight > maxHeight) {
- // Resize with height instead
- newWidth = fullsizeImage.Width * maxHeight / fullsizeImage.Height;
- newHeight = maxHeight;
- }
- }
- using(Image newImage = fullsizeImage.GetThumbnailImage(newWidth,newHeight,null,IntPtr.Zero)) {
- // Clear handle to original file so that we can overwrite it if necessary
- fullsizeImage.Dispose();
- // Save resized picture
- newImage.Save(newFile);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment