/ Published in: C#
                    
                                        
                            
                                Expand |
                                Embed | Plain Text
                            
                        
                        Copy this code and paste it in your HTML
/// <summary>
/// Allows for image resizing. if AllowLargerImageCreation = true
/// you want to increase the size of the image
/// </summary>
/// <param name="bytes"></param>
/// <param name="NewWidth"></param>
/// <param name="MaxHeight"></param>
/// <param name="AllowLargerImageCreation"></param>
/// <returns></returns>
/// <remarks></remarks>
public static byte[] ResizeImage(byte[] bytes, int NewWidth, int MaxHeight, bool AllowLargerImageCreation)
{
Image FullsizeImage = null;
Image ResizedImage = null;
//Cast bytes to an image
FullsizeImage = byteArrayToImage(bytes);
// Prevent using images internal thumbnail
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
// If we are re sizing upwards to a bigger size
if (AllowLargerImageCreation) {
if (FullsizeImage.Width <= NewWidth) {
NewWidth = FullsizeImage.Width;
}
}
//Keep aspect ratio
int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
if (NewHeight > MaxHeight) {
// Resize with height instead
NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
NewHeight = MaxHeight;
}
ResizedImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);
// Clear handle to original file so that we can overwrite it if necessary
FullsizeImage.Dispose();
return imageToByteArray(ResizedImage);
}
/// <summary>
/// convert image to byte array
/// </summary>
/// <param name="imageIn"></param>
/// <returns></returns>
private static byte[] imageToByteArray(System.Drawing.Image imageIn)
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
/// <summary>
/// Convert a byte array to an image
/// </summary>
/// <remarks></remarks>
public static Image byteArrayToImage(byte[] byteArrayIn)
{
Image returnImage = Image.FromStream(ms);
return returnImage;
}
Comments
 Subscribe to comments
                    Subscribe to comments
                
                