I'm trying to resize an image uploaded through an MVC3 app. The code below is able to resize the image based on my target sizes based on the parameter specified, however the end result is a grainy image. I've tried a lot of different solutions here in stackoverflow and msn samples but everything returns a grainy image.
static public Image ResizeFile(HttpPostedFileBase file, int targeWidth, int targetHeight)
{
Image originalImage = null;
bool IsImage = true;
Bitmap bitmap = null;
try
{
originalImage = Image.FromStream(file.InputStream, true, true);
}
catch
{
IsImage = false;
}
if (IsImage)
{
//accept an image only if it is less than 3mb(max)
if (file.ContentLength <= 3145728)
{
var newImage = new MemoryStream();
Rectangle origRect = new Rectangle(0, 0, originalImage.Width, originalImage.Height);
// if targets are null, require scale. for specified sized images eg. Event Image, or Profile photos.
int newWidth = 0;
int newHeight = 0;
//if the width is greater than height
if (originalImage.Width > originalImage.Height)
{
newWidth = targeWidth;
newHeight = targetHeight;
bitmap = new Bitmap(newWidth, newHeight);
}
//if the size of image is larger than either one of the target size
else if (originalImage.Width > targeWidth || originalImage.Height > targetHeight)
{
newWidth = targeWidth;
newHeight = targetHeight;
bitmap = new Bitmap(newWidth, newHeight);
}
//reuse old dimensions
else
{
bitmap = new Bitmap(originalImage.Width, originalImage.Height);
}
try
{
using (Graphics g = Graphics.FromImage((Image)bitmap))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(originalImage, new Rectangle(0, 0, newWidth, newHeight),
0,
0, // upper-left corner of source rectangle
originalImage.Width, // width of source rectangle
originalImage.Height, // height of source rectangle
GraphicsUnit.Pixel);
bitmap.Save(newImage, ImageFormat.Jpeg);
}
}
catch (Exception ex)
{ // error before IDisposable ownership transfer
if (bitmap != null)
bitmap.Dispose();
logger.Info("Domain/Utilities/ImageResizer->ResizeFile: " + ex.ToString());
throw new Exception("Error resizing file.");
}
}
}
return (Image)bitmap;
}
UPDATE 1
removed parameters and encoders, currently saving in .jpeg. But still produces a grainy image.
A couple of suggestions
1) Make sure that you aren't enlarging the image.
2) Try g.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias instead of HighQuality
Failing the above, I'd remove all other option settings aside from the above, and then simply save the file using;
bitmap.Save(newImage, Imaging.ImageFormat.Jpeg);
I find the above works perfectly well.
Related
I am using C#,MVC5 and I am uploading image from my web application but I realize that I have performance issues because I don't optimize them and I need to fix it and is important to keep the quality.
Below you can see the results of the report why is slow.
How can I do it?
I am saving the files into a path locally with the below code.
string imgpathvalue = ConfigurationManager.AppSettings["RestaurantPath"];
string path = System.IO.Path.Combine(Server.MapPath(imgpathvalue));
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string pic = System.IO.Path.GetFileName(restaurantImg.FileName.Replace(" ", "_").Replace("%", "_"));
path = System.IO.Path.Combine(Server.MapPath(imgpathvalue), pic);
// file is uploaded
restaurantImg.SaveAs(path);
I have try the code below but I am getting the error "A generic error occurred in GDI+."
System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(restaurantImg.InputStream);
System.Drawing.Image objImage = ResizeImages.ScaleImage(bmpPostedImage, 81);
using (var ms = new MemoryStream())
{
objImage.Save(ms, objImage.RawFormat);
//ResizeImages.getImage(ms.ToArray());
}
public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
{
var ratio = (double)maxHeight / image.Height;
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var g = Graphics.FromImage(newImage))
{
g.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}
You are missing some of the code to resize your image correctly. Appending is a function that correctly resizes images depending on the Width and Height Values you give to it (in this example the image gets resized to 120*120 if possible).
Function Call:
ResizeImage("Path to the Image you want to resize",
"Path you want to save resizes copy into", 120, 120);
To make a function call like that possible we need to write our function. Which takes the image from the sourceImagePath and creates a new Bitmap.
Then it calculates the factor to resize the image and depending on if either the width or height is bigger it gets adjusted accordingly.
After that is done we create a new BitMap fromt he sourceImagePath and resize it. At the end we also need to dispose the sourceImage, the destImage and we also need to dispose of the Graphics Element g that we used for different Quality Settings.
Resize Function:
private void ResizeImage(string sourceImagePath, string destImagePath,
int wishImageWidth, int wishImageHeight)
{
Bitmap sourceImage = new Bitmap(sourceImagePath);
Bitmap destImage = null;
Graphics g = null;
int destImageWidth = 0;
int destImageHeight = 0;
// Calculate factor of image
double faktor = (double) sourceImage.Width / (double) sourceImage.Height;
if (faktor >= 1.0) // Landscape
{
destImageWidth = wishImageWidth;
destImageHeight = (int) (destImageWidth / faktor);
}
else // Port
{
destImageHeight = wishImageHeight;
destImageWidth = (int) (destImageHeight * faktor);
}
try
{
destImage = new Bitmap(sourceImage, destImageWidth, destImageHeight);
g = Graphics.FromImage(destImage);
g.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.SmoothingMode =
System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode =
System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.CompositingQuality =
System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(sourceImage, 0, 0, destImageWidth, destImageHeight);
// Making sure that the file doesn't already exists.
if (File.Exists(destImagePath)) {
// If it does delete the old version.
File.Delete(destImagePath);
}
destImage.Save(destImagePath);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("*** ERROR-Terror: " + ex.Message)
}
finally
{
if (g != null) { g.Dispose(); g = null; }
if (destImage != null) { destImage.Dispose(); destImage = null; }
}
sourceImage.Dispose();
sourceImage = null;
}
I've seen a ton of stackoverflow articles for reducing image size, but none of them maintain the original image type (or so I've found). They usually have steps to reduce pixel dimensions, reduce image quality, and convert to a specific type of image (usually jpeg).
I have a group of images that I need to resize. They have various image types, and the filenames are all stored in a database, which makes converting from one image type to another somewhat problematic. I can't just change the filename from png to jpg because then the database won't point at a real file.
Doe anyone have an example of how to resize / reduce images to '256 kilobytes' and maintain the original image type?
For examples, here is the code I'm currently fiddling with.
public static byte[] ResizeImageFile(Image oldImage, int targetSize) // Set targetSize to 1024
{
Size newSize = CalculateDimensions(oldImage.Size, targetSize);
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
{
using (Graphics canvas = Graphics.FromImage(newImage))
{
canvas.SmoothingMode = SmoothingMode.AntiAlias;
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
MemoryStream m = new MemoryStream();
newImage.Save(m, ImageFormat.Jpeg);
return m.GetBuffer();
}
}
}
Maybe there is a way I can get file fileinfo or mime type first and then switch on the .Save for the type of image?
Here is what I came up with (based on some examples that I found online that weren't 100% complete.
private void EnsureImageRequirements(string filePath)
{
try
{
if (File.Exists(filePath))
{
// If images are larger than 300 kilobytes
FileInfo fInfo = new FileInfo(filePath);
if (fInfo.Length > 300000)
{
Image oldImage = Image.FromFile(filePath);
ImageFormat originalFormat = oldImage.RawFormat;
// manipulate the image / Resize
Image tempImage = RefactorImage(oldImage, 1200); ;
// Dispose before deleting the file
oldImage.Dispose();
// Delete the existing file and copy the image to it
File.Delete(filePath);
// Ensure encoding quality is set to an acceptable level
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
// Set encoder to fifty percent compression
EncoderParameters eps = new EncoderParameters
{
Param = { [0] = new EncoderParameter(Encoder.Quality, 50L) }
};
ImageCodecInfo ici = (from codec in encoders where codec.FormatID == originalFormat.Guid select codec).FirstOrDefault();
// Save the reformatted image and use original file format (jpeg / png / etc) and encoding
tempImage.Save(filePath, ici, eps);
// Clean up RAM
tempImage.Dispose();
}
}
}
catch (Exception ex)
{
this._logger.Error("Could not resize oversized image " + filePath, ex);
}
}
private static Image RefactorImage(Image imgToResize, int maxPixels)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
int destWidth = sourceWidth;
int destHeight = sourceHeight;
// Resize if needed
if (sourceWidth > maxPixels || sourceHeight > maxPixels)
{
float thePercent = 0;
float thePercentW = 0;
float thePercentH = 0;
thePercentW = maxPixels / (float) sourceWidth;
thePercentH = maxPixels / (float) sourceHeight;
if (thePercentH < thePercentW)
{
thePercent = thePercentH;
}
else
{
thePercent = thePercentW;
}
destWidth = (int)(sourceWidth * thePercent);
destHeight = (int)(sourceHeight * thePercent);
}
Bitmap tmpImage = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(tmpImage);
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return tmpImage;
}
i want to watermark pictures with different sizes in one folder. the watermark has 3891 x 4118 pixels. the pictures i want to watermark have nearly the same size or way lower.
however, the watermark image should always have the same size on the images. therefore i take the width of image i want to watermark, multiple it by 0.2 (20%) and the height of the watermark image gets calculated by the ratio. (see code below).
after that, i resize the watermark image and put it on on the image i want to watermark. so far so good, but the problem is, that the image is way smaller than it should be. the calculation works fine, even if i say, put the image as is (3891 x 4118 pixel), it calculates it correctly, but the watermark doesn't get bigger. it stays on a size i didn't calulcate.
that's the button to load the folder.
private void DateiLaden_Click(object sender, RoutedEventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
try
{
string[] files = GetFiles(fbd.SelectedPath.ToString(), "*.jpg|*.jpeg"); //Only select JPG pictures, method below
int anzahlBilder = files.Length;
if (anzahlBilder <= 0)
{
System.Windows.Forms.MessageBox.Show("No images!");
} // if there are no images, stop processing...
else
{
var res = checkImageSize(files); //check if they have a minmal size, method below
if (res == "") //if everythings fine, continue
{
Directory.CreateDirectory(fbd.SelectedPath.ToString() + "\\watermarked"); //create new directory of the selected folder, folder so save the watermarked images
System.Drawing.Image brand = System.Drawing.Image.FromFile("../../watermark.png"); //load watermark
double imageHeightBrand = Convert.ToDouble(brand.Height); //get height (4118px)
double imageWidthBrand = Convert.ToDouble(brand.Width); //get width (3891px)
double ratioBrand = imageWidthBrand / imageHeightBrand; //get ratio (0.94487615347)
foreach (var file in files)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(file); //load image to watermerk to get width and height
double imageHeightBild = Convert.ToDouble(img.Height); //height of the image to watermark
double imageWidthBild = Convert.ToDouble(img.Width); //width of the image to watermark
//Landscape
if (imageWidthBild > 640.0 && imageHeightBild > 425.0)
{
var imageWidthTmpBranding = imageWidthBild * 0.2; //the watermark width, but only 20% size of the image to watermark
var imageHeightTmpBranding = imageWidthTmpBranding / ratioBrand; //height of watermark, preserve aspect ratio
int imageWidthBranding = Convert.ToInt32(imageWidthTmpBranding); //convert in into int32 (see method below)
int imageHeightBranding = Convert.ToInt32(imageHeightTmpBranding); //convert in into int32 (see method below)
var watermark = ResizeImage(brand, imageWidthBranding, imageHeightBranding); //resize temporally the watermark image, method below
System.Drawing.Image image = System.Drawing.Image.FromFile(file); //get image to watermark
Graphics g = Graphics.FromImage(image); //load is as graphic
g.DrawImage(watermark, new System.Drawing.Point(50, 50)); //draw the watermark on it
image.Save(fbd.SelectedPath.ToString() + "\\watermarked\\" + returnOnlyImageName(file)); //save it in the folder with the same file name, see method below.
}
//Portrait
/* if(imageWidthBild > 350 && imageHeightBild > 520) {
}*/
}
}
else
{
System.Windows.Forms.MessageBox.Show(res);
}
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
"methods below"
private static string[] GetFiles(string sourceFolder, string filters)
{
return filters.Split('|').SelectMany(filter => System.IO.Directory.GetFiles(sourceFolder, filter)).ToArray();
}
private static string checkImageSize(string[] files)
{
string message = "The following pictures are too small:\n";
foreach (var file in files)
{
Bitmap img = new Bitmap(file);
var imageHeight = img.Height;
var imageWidth = img.Width;
if ((imageWidth < 640 && imageHeight < 425) || (imageWidth < 350 && imageHeight < 520))
{
message += returnOnlyImageName(file) + "\n";
}
}
if (message == "The following pictures are too small:\n")
{
return "";
}
else
{
message += "\nPlease change those pictures!";
return message;
}
}
private static string returnOnlyImageName(string file)
{
return file.Substring(file.LastIndexOf("\\")+1);
}
public static Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
{
var destRect = new System.Drawing.Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
and is it also anyhow possible to save all the watermarks in the bottom right corner?
thanks in regards
Here you go...
void waterMarkOnBottomRight(Image img, Image watermarkImage, string saveFileName)
{
double imageHeightBrand = Convert.ToDouble(watermarkImage.Height);
double imageWidthBrand = Convert.ToDouble(watermarkImage.Width);
double ratioBrand = imageWidthBrand / imageHeightBrand;
double imageHeightBild = Convert.ToDouble(img.Height); //height of the image to watermark
double imageWidthBild = Convert.ToDouble(img.Width);
var imageWidthTmpBranding = imageWidthBild * 0.2; //the watermark width, but only 20% size of the image to watermark
var imageHeightTmpBranding = imageWidthTmpBranding / ratioBrand; //height of watermark, preserve aspect ratio
int imageWidthBranding = Convert.ToInt32(imageWidthTmpBranding); //convert in into int32 (see method below)
int imageHeightBranding = Convert.ToInt32(imageHeightTmpBranding);
int watermarkX = (int)(imageWidthBild - imageWidthBranding); // Bottom Right
int watermarkY = (int)(imageHeightBild - imageHeightBranding);
using (Graphics g = Graphics.FromImage(img))
g.DrawImage(watermarkImage,
new Rectangle(watermarkX, watermarkY, imageWidthBranding, imageHeightBranding),
new Rectangle(0, 0, (int)imageWidthBrand, (int)imageHeightBrand),
GraphicsUnit.Pixel);
img.Save(saveFileName);
}
This one's working for landscape (width > height).
Well.. in your code, you don't have to create separate instances for images for calculating, for creating graphics, add a new bitmap and paint using graphics and all. You do anything with the image, its in the memory. And its not going to affect the watermark image on your disk.
I'm using the following code to resize images on upload. The problem is that the new image size is big. I tried changing the interpolation to low and the composition quality the High Speed but nothing seems to work. Sometimes the new smaller and resized image is as big in file size as its original uploaded image. There are other properties to use for the System.Drawing.Drawing2D but which one can affect the file size? any tips?
private static Bitmap ResizeBitmap(Bitmap b, int nWidth)
{
int nHeight = CalculateProportionalHeight(b.Width, b.Height, nWidth);
Bitmap result = new Bitmap(nWidth, nHeight);
result.SetResolution(72.0F, 72.0F);
Graphics g = Graphics.FromImage((System.Drawing.Image)result);
g.InterpolationMode = InterpolationMode.Low;
g.CompositingQuality = CompositingQuality.HighSpeed;
g.DrawImage(b, 0, 0, nWidth, nHeight);
return result;
}
In my original answer I posted this code assuming that it was not having the same issue you were with file size inflation... I was wrong. So after some tinkering, I realized that my JPG images were being saved with a JPG extension... but encoded as PNG, thus the increase in file size. Here is an updated codebase, tested reliable with PNG, GIF, and JPG. The file size will be lower when the image is smaller than the original.
First a basic method that takes a Bitmap and resizes it.
public static Bitmap Resize(Bitmap imgPhoto, Size objSize, ImageFormat enuType)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
int destWidth = objSize.Width;
int destHeight = objSize.Height;
Bitmap bmPhoto;
if (enuType == ImageFormat.Png)
bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format32bppArgb);
else if (enuType == ImageFormat.Gif)
bmPhoto = new Bitmap(destWidth, destHeight); //PixelFormat.Format8bppIndexed should be the right value for a GIF, but will throw an error with some GIF images so it's not safe to specify.
else
bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
//For some reason the resolution properties will be 96, even when the source image is different, so this matching does not appear to be reliable.
//bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
//If you want to override the default 96dpi resolution do it here
//bmPhoto.SetResolution(72, 72);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
Here's how to use the Resize method...
String strImageFile = Server.MapPath("/Images/ImageFile.jpg");
System.Drawing.Bitmap objImage = new System.Drawing.Bitmap(strImageFile);
System.Drawing.Size objNewSize = new System.Drawing.Size(100, 50);
System.Drawing.Bitmap objNewImage = Resize(objImage, objNewSize, ImageFormat.Jpeg);
objNewImage.Save(Server.MapPath("/Images/FileName_Resized.jpg"), ImageFormat.Jpeg);
objNewImage.Dispose();
This method adds a layer of complexity, you can define a maximum size constraint, and the method will Resize the image to stay in proportion... but be no larger than... the maximum size. It will leave the image alone if it is less than or equal to the max size, returning the original Bitmap instead.
public static Bitmap SmartResize(string strImageFile, Size objMaxSize, ImageFormat enuType)
{
Bitmap objImage = null;
try
{
objImage = new Bitmap(strImageFile);
}
catch (Exception ex)
{
throw ex;
}
if (objImage.Width > objMaxSize.Width || objImage.Height > objMaxSize.Height)
{
Size objSize;
int intWidthOverrun = 0;
int intHeightOverrun = 0;
if (objImage.Width > objMaxSize.Width)
intWidthOverrun = objImage.Width - objMaxSize.Width;
if (objImage.Height > objMaxSize.Height)
intHeightOverrun = objImage.Height - objMaxSize.Height;
double dblRatio;
double dblWidthRatio = (double)objMaxSize.Width / (double)objImage.Width;
double dblHeightRatio = (double)objMaxSize.Height / (double)objImage.Height;
if (dblWidthRatio < dblHeightRatio)
dblRatio = dblWidthRatio;
else
dblRatio = dblHeightRatio;
objSize = new Size((int)((double)objImage.Width * dblRatio), (int)((double)objImage.Height * dblRatio));
Bitmap objNewImage = Resize(objImage, objSize, enuType);
objImage.Dispose();
return objNewImage;
}
else
{
return objImage;
}
}
Here's how to implement it...
String strImageFile = Server.MapPath("/Images/ImageFile.png");
System.Drawing.Size objMaxSize = new System.Drawing.Size(100, 100);
System.Drawing.Bitmap objNewImage = SmartResize(strImageFile, objMaxSize, ImageFormat.Png);
objNewImage.Save(Server.MapPath("/Images/FileName_Resized.png"), ImageFormat.Png);
objNewImage.Dispose();
I've got to following function which is called to change the resolution of an image. I want to do this so uploaded image with for example 300dpi will be modified to 72dpi (for web). This question is related to another question here on SO where i'm working on.
I'm creation an extension method for this to be able to use this function on more places in my application, instead of only when uploading new files. (See above mentioned question)
public static byte[] SetDpiTo72(this byte[] imageToFit, string mimeType, Size newSize)
{
using (MemoryStream memoryStream = new MemoryStream(), newMemoryStream = new MemoryStream())
{
memoryStream.Write(imageToFit, 0, imageToFit.Length);
var originalImage = new Bitmap(memoryStream);
using (var canvas = Graphics.FromImage(originalImage))
{
canvas.SmoothingMode = SmoothingMode.AntiAlias;
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage((Image)originalImage,0,0, newSize.Width, newSize.Height);
newBitmap.SetResolution(72, 72);
newBitmap.Save(newMemoryStream, ImageFunctions.GetEncoderInfo(mimeType), null);
}
return newMemoryStream.ToArray();
}
}
The mentioned extension methode is being called in a function similar to the situation below;
if (newSize.Width > originalImage.Width && newSize.Height > originalImage.Height)
{
newSize.Width = originalImage.Width;
newSize.Height = originalImage.Height;
uploadedFileBuffer = uploadedFileBuffer.SetDpiTo72(uploadedFile.ContentType, newSize);
return CreateFile(newSize, uploadedFile, uploadedFileBuffer);
}
The bytearray coming in is the file as an bytearray. It already has the correct size, but I want to change the resolution to 72dpi. However after exectution and saving the image the resolution is still the originale entered resolution, which is 300dpi. How can I do this?
UPDATE AFTER SEVERAL ANSWERS:
public static byte[] SetDpiTo72(this byte[] imageToFit, string mimeType, Size newSize)
{
using (MemoryStream memoryStream = new MemoryStream(), newMemoryStream = new MemoryStream())
{
memoryStream.Write(imageToFit, 0, imageToFit.Length);
var originalImage = new Bitmap(memoryStream);
using (var canvas = Graphics.FromImage(originalImage))
{
canvas.SmoothingMode = SmoothingMode.AntiAlias;
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage((Image)originalImage,0,0, newSize.Width, newSize.Height);
originalImage.SetResolution(72, 72);
var epQuality = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75);
var epParameters = new EncoderParameters(1);
epParameters.Param[0] = epQuality;
Image newimg = Image.FromStream(memoryStream);
//Getting an GDI+ exception after the execution of this line.
newimg.Save("C:\\test1234.jpg", ImageFunctions.GetEncoderInfo(mimeType), epParameters);
originalImage.Save("test.jpg", ImageFormat.Jpeg);
//This line give me an Argumentexception - Parameter is not valid.
//originalImage.Save(newMemoryStream, ImageFunctions.GetEncoderInfo(mimeType), epParameters);
//newMemoryStream.Close();
}
return newMemoryStream.ToArray();
}
}
The stackstrace which comes with the exception is telling me the following;
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
at Extensions.ByteArrayExtensions.SetDpiTo72(Byte[] imageToFit, String mimeType, Size newSize) in C:\Website\Project\Extensions\ByteArrayExtensions.cs:line 356
at CMS.Presentation.FileFunctions.CreateFullsizeImage(HttpPostedFileBase uploadedFile, Size newSize, Byte[] uploadedFileBuffer) in C:\Website\Project\CMS.Presentation\FileFunctions.cs:line 197
at CMS.Presentation.FileFunctions.CreateFile(HttpPostedFileBase uploadedFile, INodeService nodeservice, Guid userId, Node parentNode) in C:\Website\Project\CMS.Presentation\FileFunctions.cs:line 53
In the mean time I've also developed another function (see below) resizing just a bitmap. And this seem to work correctly. I can't use this function with my current implementation though because it returns just an Bitmap. Or should i change everything to work with bitmaps?
private static Bitmap ResizeImage(Image image, int width, int height)
{
var frameCount = image.GetFrameCount(new FrameDimension(image.FrameDimensionsList[0]));
var newDimensions = ImageFunctions.GenerateImageDimensions(image.Width, image.Height, width, height);
Bitmap resizedImage;
if (frameCount > 1)
{
//we have a animated GIF
resizedImage = ResizeAnimatedGifImage(image, width, height);
}
else
{
resizedImage = (Bitmap)image.GetThumbnailImage(newDimensions.Width, newDimensions.Height, null, IntPtr.Zero);
}
resizedImage.SetResolution(72,72);
return resizedImage;
}
Ok, I tried it only on files on harddrive, but it should work with streams too.
Bitmap bitmap = new Bitmap(loadFrom);
Bitmap newBitmap = new Bitmap(bitmap);
newBitmap.SetResolution(72, 72);
newBitmap.Save(saveTo);
Took me a while, but I finally found the problem!
The problem lied in the ResizeImage function I used. In the 'GetThumbnailImage' to be specific. I ran into another problem with blurry images, which was explainable because GetThumbnailImage would stretch up the created ThumbNail to the desired size. And the resolution off the thumbnail never changes.
private static Bitmap ResizeImage(Image image, int width, int height)
{
var frameCount = image.GetFrameCount(new FrameDimension(image.FrameDimensionsList[0]));
var newDimensions = ImageFunctions.GenerateImageDimensions(image.Width, image.Height, width, height);
Bitmap resizedImage;
if (frameCount > 1)
{
//we have a animated GIF
resizedImage = ResizeAnimatedGifImage(image, width, height);
}
else
{
resizedImage = (Bitmap)image.GetThumbnailImage(newDimensions.Width, newDimensions.Height, null, IntPtr.Zero);
}
resizedImage.SetResolution(72,72);
return resizedImage;
}
By modifying the function above to the function below I was able to solve the problem using Graphics.DrawImage to redraw the new image before rendering it. Also the GenerateImageDimensions was slightly modified. This taken together the problem was solved.
private static Bitmap ResizeImage(Image image, int width, int height)
{
var frameCount = image.GetFrameCount(new FrameDimension(image.FrameDimensionsList[0]));
var newDimensions = ImageFunctions.GenerateImageDimensions(image.Width, image.Height, width, height);
var resizedImage = new Bitmap(newDimensions.Width, newDimensions.Height);
if (frameCount > 1)
{
//we have a animated GIF
resizedImage = ResizeAnimatedGifImage(image, width, height);
}
else
{
//we have a normal image
using (var gfx = Graphics.FromImage(resizedImage))
{
gfx.SmoothingMode = SmoothingMode.HighQuality;
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
var targRectangle = new Rectangle(0, 0, newDimensions.Width, newDimensions.Height);
var srcRectangle = new Rectangle(0, 0, image.Width, image.Height);
gfx.DrawImage(image, targRectangle, srcRectangle, GraphicsUnit.Pixel);
}
}
return resizedImage;
}
By "changing the resolution", do you actually mean you want to reduce the number of pixels in the image by 72/300? I.e. change a 4000x3000 image to 960x720?
If so, I can't see where your code actually does that. The overload of DrawImage() you're using does this:
Draws the specified image, using its original physical size, at the location specified by a coordinate pair.
Which is exactly what is happening.
Try one of the other overloads such as this one:
Draws the specified Image at the specified location and with the specified size.
for example:
// Create image.
Image newImage = Image.FromFile("SampImag.jpg");
// Create coordinates for upper-left corner of image and for size of image.
int x = 0;
int y = 0;
int width = 450;
int height = 150;
// Draw image to screen.
e.Graphics.DrawImage(newImage, x, y, width, height);
EDIT: per the comments, I understand the OP wants to reduce file size without reducing pixel count. Therefore the files must be recompressed.
I've borrowed some sample code from here:
ImageCodecInfo iciJpegCodec = null;
// This will specify the image quality to the encoder. Change the value of 75 from 0 to 100, where 100 is best quality, but highest file size.
EncoderParameter epQuality = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75);
// Get all image codecs that are available
ImageCodecInfo[] iciCodecs = ImageCodecInfo.GetImageEncoders();
// Store the quality parameter in the list of encoder parameters
EncoderParameters epParameters = new EncoderParameters(1);
epParameters.Param[0] = epQuality;
// Loop through all the image codecs
for (int i = 0; i < iciCodecs.Length; i++)
{
// Until the one that we are interested in is found, which is image/jpeg
if (iciCodecs[i].MimeType == "image/jpeg")
{
iciJpegCodec = iciCodecs[i];
break;
}
}
// Create a new Image object from the current file
Image newImage = Image.FromFile(strFile);
// Get the file information again, this time we want to find out the extension
FileInfo fiPicture = new FileInfo(strFile);
// Save the new file at the selected path with the specified encoder parameters, and reuse the same file name
newImage.Save(outputPath + "\\" + fiPicture.Name, iciJpegCodec, epParameters);
Rob, I believe that issue with your code is at saving the image - the actual digital image data would be certain number of dots/pixels i.e. (m x n) and setting resolution at bitmap wouldn't/shouldn't change the number dots (and hence physical byte size of image). The resolution information will be stored in the image header (to be used by programs while printing/editing images) - what happens if you store the new bitmap to file instead of mem stream
newBitmap.Save("c:\test.png", ImageFormat.Png);
Check dpi for above file from file -> properties -> summary (advanced). It should be 72 dpi.