I'm working on a service for a company project that handles image processing, and one of the methods is supposed to clean the metadata from an image passed to it.
I think implementation I currently have works, but I'm not sure if it's affecting the quality of images or if there's a better way to handle this task. Could you let me know if you know of a better way to do this?
Here's the method in question:
public byte[] CleanMetadata(byte[] data)
{
Image image;
if (tryGetImageFromBytes(data, out image))
{
Bitmap bitmap = new Bitmap(image);
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(image, new Point(0, 0));
}
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(image, typeof(byte[]));
}
return null;
}
And, for reference, the tryGetImageFromBytes method:
private bool tryGetImageFromBytes(byte[] data, out Image image)
{
try
{
using (var ms = new MemoryStream(data))
{
image = Image.FromStream(ms);
}
}
catch (ArgumentException)
{
image = null;
return false;
}
return true;
}
To reiterate: is there a better way to remove metadata from an image that doesn't involve redrawing it?
Thanks in advance.
The .NET way: You may want to try your hand at the System.Windows.Media.Imaging.BitmapEncoder class - more precisely, its Metadata collection. Quoting MSDN:
Metadata - Gets or sets the metadata that will be associated with this
bitmap during encoding.
The 'Oops, I (not so accidentally) forgot something way: Open the original bitmap file into a System.drawing.Bitmap object. Clone it to a new Bitmap object. Write the clone's contents to a new file. Like this one-liner:
((System.Drawing.Bitmap)System.Drawing.Image.FromFile(#"C:\file.png").Clone()).Save(#"C:\file-nometa.png");
The direct file manipulation way (only for JPEG): Blog post about removing the EXIF area.
I would suggest this, the source is here: Removing Exif-Data for jpg file
Changing a bit the 1st function
public Stream PatchAwayExif(Stream inStream)
{
Stream outStream = new MemoryStream();
byte[] jpegHeader = new byte[2];
jpegHeader[0] = (byte)inStream.ReadByte();
jpegHeader[1] = (byte)inStream.ReadByte();
if (jpegHeader[0] == 0xff && jpegHeader[1] == 0xd8) //check if it's a jpeg file
{
SkipAppHeaderSection(inStream);
}
outStream.WriteByte(0xff);
outStream.WriteByte(0xd8);
int readCount;
byte[] readBuffer = new byte[4096];
while ((readCount = inStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
outStream.Write(readBuffer, 0, readCount);
return outStream;
}
And the second function with no changes, as post
private void SkipAppHeaderSection(Stream inStream)
{
byte[] header = new byte[2];
header[0] = (byte)inStream.ReadByte();
header[1] = (byte)inStream.ReadByte();
while (header[0] == 0xff && (header[1] >= 0xe0 && header[1] <= 0xef))
{
int exifLength = inStream.ReadByte();
exifLength = exifLength << 8;
exifLength |= inStream.ReadByte();
for (int i = 0; i < exifLength - 2; i++)
{
inStream.ReadByte();
}
header[0] = (byte)inStream.ReadByte();
header[1] = (byte)inStream.ReadByte();
}
inStream.Position -= 2; //skip back two bytes
}
Creating a new bitmap will clear out all the exif data.
var newImage = new Bitmap(image);
If you want to remove only specific info:
private Image RemoveGpsExifInfo(Image image)
{
foreach (var item in image.PropertyItems)
{
// GPS range is from 0x0000 to 0x001F. Full list here -> https://exiftool.org/TagNames/EXIF.html (click on GPS tags)
if (item.Id <= 0x001F)
{
image.RemovePropertyItem(item.Id);
}
}
return image;
}
Related
I am trying to generate a gif using Bumpkit gif encoder and while the gif works (Except for the first frames acting out), when I try to load the gif in photoshop, it says "Could not complete request because the file-format module cannot parse the file".
I don't know how to check the validity of the gif because it works when I view it. This is how Im using the Bumpkit library:
public void SaveImagesAsGif(Stream stream, ICollection<Bitmap> images, float fps, bool loop)
{
if (images == null || images.ToArray().Length == 0)
{
throw new ArgumentException("There are no images to add to animation");
}
int loopCount = 0;
if (!loop)
{
loopCount = 1;
}
using (var encoder = new BumpKit.GifEncoder(stream, null, null, loopCount))
{
foreach (Bitmap bitmap in images)
{
encoder.AddFrame(bitmap, 0, 0, TimeSpan.FromSeconds(1 / fps));
}
}
stream.Position = 0;
}
Am I doing something wrong when generating the gif?
When you are using the Bumpkit gif encoder library, I think you have to call the InitHeader function first.
Take from the GifEncoder.cs source:
private void InitHeader(Stream sourceGif, int w, int h)
You can see the source code for the InitHeader function, the AddFrame function and the rest of the GifEncoder.cs file at https://github.com/DataDink/Bumpkit/blob/master/BumpKit/BumpKit/GifEncoder.cs
So it's a small edit to your code:
public void SaveImagesAsGif(Stream stream, ICollection<Bitmap> images, float fps, bool loop)
{
if (images == null || images.ToArray().Length == 0)
{
throw new ArgumentException("There are no images to add to animation");
}
int loopCount = 0;
if (!loop)
{
loopCount = 1;
}
using (var encoder = new BumpKit.GifEncoder(stream, null, null, loopCount))
{
//calling initheader function
//TODO: Change YOURGIFWIDTHHERE and YOURGIFHEIGHTHERE to desired width and height for gif
encoder.InitHeader(stream, YOURGIFWIDTHHERE, YOURGIFHEIGHTHERE);
foreach (Bitmap bitmap in images)
{
encoder.AddFrame(bitmap, 0, 0, TimeSpan.FromSeconds(1 / fps));
}
}
stream.Position = 0;
}
Here is my Code, I am trying to stitch two pictures together and as soon as I get to line 42 "Image img = Image.FromFile(file.FullName);" I get an out of memory error. What should I do?
namespace Practicing_Stiching
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void cmdCombine_Click(object sender, EventArgs e)
{
//Change the path to location where your images are stored.
DirectoryInfo directory = new DirectoryInfo(#"C:\Users\Elder Zollinger\Desktop\Images");
if (directory != null)
{
FileInfo[] files = directory.GetFiles();
CombineImages(files);
}
}
private void CombineImages(FileInfo[] files)
{
//change the location to store the final image.
string finalImage = #"C:\Users\Elder Zollinger\Desktop\Images";
List<int> imageHeights = new List<int>();
int nIndex = 0;
int width = 0;
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
}
imageHeights.Sort();
int height = imageHeights[imageHeights.Count - 1];
Bitmap img3 = new Bitmap(width, height);
Graphics g = Graphics.FromImage(img3);
g.Clear(SystemColors.AppWorkspace);
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
if (nIndex == 0)
{
g.DrawImage(img, new Point(0, 0));
nIndex++;
width = img.Width;
}
else
{
g.DrawImage(img, new Point(width, 0));
width += img.Width;
}
img.Dispose();
}
g.Dispose();
img3.Save(finalImage, System.Drawing.Imaging.ImageFormat.Jpeg);
img3.Dispose();
imageLocation.Image = Image.FromFile(finalImage);
}
}
}
That's likely GDI playing tricks on you.
You see, when GDI encounters an unknown file, it will quite likely cause an OutOfMemoryException. Since you're not filtering the input images at all, I'd expect that you're simply grabbing a non-image file (or an image type that GDI doesn't understand).
Oh, and a bit sideways - make sure you set JPEG quality when saving JPEGs - the default is something like 75, which is rather bad for a lot of images. And please, do use using - it's very handy to ensure proper and timely clean-up :)
Get more memory!
But seriously, you don't appear to be filtering out files that are not image files. There are some hidden files in folders that you may be trying to open as an image accidentally, such as "Thumbs.db". Make sure that the file is an image with something like if (Path.GetExtension(file.FullPath) != ".png") continue;.
Also, on objects that you are calling .Dispose() on, consider wrapping them in a using() instead. For example:
using(var img = Image.FromFile(file.FullPath))
{
// ...
}
I have been exhausted from this error from last 2 weeks.I tried a lot to find out and tried the code in different way but not succeeded yet.I think the main problem is with bitmap, may be i am not using in right way.I am sharing my code for help to understand what i am doing.
First i tell you the scenario.In this app, i am using dslr camera for live view.The main code area from camera class is here below :
internal void Run()
{
LVrunning = true;
while (LVrunning)
{
Thread.Sleep(20);
if (LVrunning)
UpdatePicture();
}
}
private void UpdatePicture()
{
try
{
if (err == EDSDK.EDS_ERR_OK && LVrunning)
{
inSide = true;
// Download live view image data
err = EDSDK.EdsDownloadEvfImage(cameraDev, EvfImageRef);
if (err != EDSDK.EDS_ERR_OK)
{
Debug.WriteLine(String.Format("Download of Evf Image: {0:X}", err));
return;
}
IntPtr ipData;
err = EDSDK.EdsGetPointer(MemStreamRef, out ipData);
if (err != EDSDK.EDS_ERR_OK)
{
Debug.WriteLine(String.Format("EdsGetPointer failed: {0:X}", err));
return;
}
uint len;
err = EDSDK.EdsGetLength(MemStreamRef, out len);
if (err != EDSDK.EDS_ERR_OK)
{
Debug.WriteLine(String.Format("EdsGetLength failed:{0:X}", err));
EDSDK.EdsRelease(ipData);
return;
}
Byte[] data = new byte[len];
Marshal.Copy(ipData, data, 0, (int)len);
System.IO.MemoryStream memStream = new System.IO.MemoryStream(data);
// get the bitmap
Bitmap bitmap = null;
try
{
bitmap = new Bitmap(memStream);
}
catch (OutOfMemoryException ex)
{
GC.WaitForPendingFinalizers();
bitmap = new Bitmap(memStream); // sometimes error occur
}
NewFrame(bitmap, null); // this is event call back to form area.
memStream.Dispose();
EDSDK.EdsRelease(ipData);
}
}
catch (Exception ex)
{
}
}
private void getCapturedItem(IntPtr directoryItem)
{
uint err = EDSDK.EDS_ERR_OK;
IntPtr stream = IntPtr.Zero;
EDSDK.EdsDirectoryItemInfo dirItemInfo;
err = EDSDK.EdsGetDirectoryItemInfo(directoryItem, out dirItemInfo);
if (err != EDSDK.EDS_ERR_OK)
{
throw new CameraException("Unable to get captured item info!", err);
}
// Fill the stream with the resulting image
if (err == EDSDK.EDS_ERR_OK)
{
err = EDSDK.EdsCreateMemoryStream((uint)dirItemInfo.Size, out stream);
}
// Copy the stream to a byte[] and
if (err == EDSDK.EDS_ERR_OK)
{
err = EDSDK.EdsDownload(directoryItem, (uint)dirItemInfo.Size, stream);
}
// Create the returned item
//CapturedItem item = new CapturedItem();
if (dirItemInfo.szFileName.ToString().ToLower().Contains("jpg") || dirItemInfo.szFileName.ToString().ToLower().Contains("jpeg"))
{
if (err == EDSDK.EDS_ERR_OK)
{
IntPtr imageRef = IntPtr.Zero;
err = EDSDK.EdsCreateImageRef(stream, out imageRef);
if (err == EDSDK.EDS_ERR_OK)
{
EDSDK.EdsImageInfo info;
err = EDSDK.EdsGetImageInfo(imageRef, EDSDK.EdsImageSource.FullView, out info);
}
}
}
if (err == EDSDK.EDS_ERR_OK)
{
try
{
byte[] buffer = new byte[(int)dirItemInfo.Size];
GCHandle gcHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr address = gcHandle.AddrOfPinnedObject();
IntPtr streamPtr = IntPtr.Zero;
err = EDSDK.EdsGetPointer(stream, out streamPtr);
if (err != EDSDK.EDS_ERR_OK)
{
throw new CameraDownloadException("Unable to get resultant image.", err);
}
try
{
Marshal.Copy(streamPtr, buffer, 0, (int)dirItemInfo.Size);//sometimes error comes here
System.IO.MemoryStream memStream = new System.IO.MemoryStream(buffer);
Bitmap bitmap = null;
try
{
bitmap = new Bitmap(memStream);
}
catch (OutOfMemoryException ex)
{
GC.WaitForPendingFinalizers();
Bitmap b = new Bitmap(memStream);//sometimes error comes here
}
if (bitmap != null)
{
PhotoCaptured(bitmap, null);
}
}
catch (AccessViolationException ave)
{
throw new CameraDownloadException("Error copying unmanaged stream to managed byte[].", ave);
}
finally
{
gcHandle.Free();
EDSDK.EdsRelease(stream);
EDSDK.EdsRelease(streamPtr);
}
}
catch (OutOfMemoryException ex)
{
GC.WaitForPendingFinalizers();
IboothmeObject.minimizeMemory();
getCapturedItem(directoryItem);
}
}
else
{
throw new CameraDownloadException("Unable to get resultant image.", err);
}
}
On form side, image is updating in picture box simply
private void StartLiveView()
{
if (this.liveView.Connected)
{
this.liveView.PhotoCaptured += new EventHandler(liveView_PhotoCaptured);
this.liveView.NewFrame += new EventHandler(liveView_NewFrame);
this.liveView.StartLiveView();
}
}
void liveView_NewFrame(object sender, EventArgs e)
{
this.picMain.Image = sender as Image;
}
void liveView_PhotoCaptured(object sender, EventArgs e)
{
Image img = sender as Image;
// this image is big in size like 5000x3000.
Bitmap tempbitmap = new Bitmap(img.Width, img.Height);// now mostly error comes here
tempbitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
using (Graphics g = Graphics.FromImage(tempbitmap))
{
g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));
g.Save();
}
picMain.Image = tempbitmap;
tempbitmap.Save(path,ImageFormat.Jpeg);
}
Another area of code which uses the bitmap and live view from camera.This code get the frame from camera and write some objects on frame..In my case, i am writing some ballons on the frame
void liveView_NewFrame(object sender, EventArgs e)
{
using (Image<Bgr, byte> Frame = new Image<Bgr, byte>(new Bitmap(sender as Image)))
{
Frame._SmoothGaussian(3);
IntPtr hsvImage = CvInvoke.cvCreateImage(CvInvoke.cvGetSize(Frame), Emgu.CV.CvEnum.IPL_DEPTH.IPL_DEPTH_8U, 3);
CvInvoke.cvCvtColor(Frame, hsvImage, Emgu.CV.CvEnum.COLOR_CONVERSION.CV_BGR2HSV);
Image<Gray, byte> imgThresh = new Image<Gray, byte>(Frame.Size);
imgThresh.Ptr = GetThresholdedImage(hsvImage);
//CvInvoke.cvSmooth(imgThresh, imgThresh, Emgu.CV.CvEnum.SMOOTH_TYPE.CV_GAUSSIAN, 3, 3, 3, 3);
#region Draw the contours of difference
//this is tasken from the ShapeDetection Example
Rectangle largest = new Rectangle();
try
{
using (MemStorage storage = new MemStorage()) //allocate storage for contour approximation
//detect the contours and loop through each of them
for (Contour<Point> contours = imgThresh.Convert<Gray, Byte>().FindContours(
Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE,
Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_EXTERNAL,
storage);
contours != null;
contours = contours.HNext)
{
//Create a contour for the current variable for us to work with
Contour<Point> currentContour = contours.ApproxPoly(contours.Perimeter * 0.05, storage);
//Draw the detected contour on the image
if (currentContour.Area > ContourThresh) //only consider contours with area greater than 100 as default then take from form control
{
if (currentContour.BoundingRectangle.Width > largest.Width && currentContour.BoundingRectangle.Height > largest.Height)
{
largest = currentContour.BoundingRectangle;
}
}
//storage.Dispose();
}
}
catch (Exception)
{
}
#endregion
#region Draw Object
Random r = new Random();
//Bitmap bb = Frame.Bitmap;
foreach (var item in objectList)
{
using (Graphics g = Graphics.FromImage(Frame.Bitmap))
{
if (DrawAble(item, largest))
{
if (item.Y < 0)
{
if (item.X < picMain.Width)
{
g.DrawImage(item.image, new Rectangle(item.X, 0, item.image.Width, item.image.Height + item.Y),
new Rectangle(), GraphicsUnit.Pixel);
item.X += r.Next(-5, 5);
item.Y += 15;
}
}
else
{
if (item.X < picMain.Width && item.Y < picMain.Height)
{
g.DrawImage(item.image, new Rectangle(item.X, item.Y, item.image.Width, item.image.Height));
item.X += r.Next(-5, 5);
item.Y += 15;
}
else
{
item.X = r.Next(0, picMain.Width - 5);
item.Y = r.Next(-item.image.Height, -5);
}
}
}
else
{
item.X = r.Next(0, picMain.Width - 5);
item.Y = r.Next(-item.image.Height, -5);
}
}
}
#endregion
picMain.Image = Frame.ToBitmap();
}
minimizeMemory();
}
Now i share the whole problem in detail.
First on all i created a form for live view and by using opencv(Emgu) library , i am drawing balloons on the frame.In live view these balloons are moving.The other form is for capture the picture from camera with high resolution.
I noticed that, my application memory was increasing with every frame and after 2 live-view and 2 pictures caputured, it goes to 1+ GB.If i tried to show first form again for live view, error occured in UpdatePicture() function.
then i add the code to minimize the memory of the current application.now i am calling this function after every frame in live-view.
After this solution when i checked the memory of application it does not go over 100mb or 200mb.
But problem was still there.after few captures, error occurred in UpdatePicture() when get bitmap from stream ( bitmap = new Bitmap(memStream);).The error was same out of memory.
After some search i found this solution.
// get the bitmap
Bitmap bitmap = null;
try
{
bitmap = new Bitmap(memStream);
}
catch (OutOfMemoryException ex)
{
GC.WaitForPendingFinalizers();
bitmap = new Bitmap(memStream);
}
But not working error is still same.
Error sometimes shown in UpdatePicture() method, sometime occurred in liveView_NewFrame method.
Means problem is related to bitmap, bitmap size or memory is corrupt.
So please help me.I am worried, 2 weeks passed but i could not solve this.
you are calling CvInvoke.cvCreateImage the created data is sitting on the native heap
so it wont be collected by the GC.
you must call cvReleaseImage(IntPtr) to release the data
there are alot of memory profilers which can help understanding the issue
try using ANTS Memory Profiler 7
i want to convert a string entered by user to an image..how can it be done?
i tried the following code but i get an argument exception in the line :
WriteableBitmap wbimg = PictureDecoder.DecodeJpeg(memStream);
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= StringToAscii(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
public static byte[] StringToAscii(string s)
{
byte[] retval = new byte[s.Length];
for (int ix = 0; ix < s.Length; ++ix)
{
char ch = s[ix];
if (ch <= 0x7f) retval[ix] = (byte)ch;
else retval[ix] = (byte)'?';
}
return retval;
}
void convert()
{
String s = textBox1.Text;
byte[] data = Convert.FromBase64String(EncodeTo64(s));
for (int i = 0; i < data.Length; i++)
{
System.Diagnostics.Debug.WriteLine(data[i]);
}
Stream memStream = new MemoryStream();
memStream.Write(data, 0, data.Length);
try
{
WriteableBitmap wbimg = PictureDecoder.DecodeJpeg(memStream);
image1.Source = wbimg;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
I got what i wanted in the following links.. How can I render text on a WriteableBitmap on a background thread, in Windows Phone 7? and http://blogs.u2u.be/michael/post/2011/04/20/Adding-a-text-to-an-image-in-WP7.aspx Thanks to all those who replied for the initial help! :)
It is the simple way you can convert TextBlock Text into Image
private void convert_Click(object sender, RoutedEventArgs e)
{
Canvas c1 = new Canvas();
TextBlock t = new TextBlock();
t.Text = text1.Text;
t.FontFamily = text1.FontFamily;
t.Foreground = text1.Foreground;
t.FontSize = text1.FontSize;
c1.Children.Add(t);
WriteableBitmap wbmp = new WriteableBitmap(c1, null);
im = new Image();
im.Source = wbmp;
im.Height = 200;
im.Width = 200;
Canvas.SetTop(im, 10);
Canvas.SetLeft(im, 10);
Main_Canvas.Children.Add(im);
}
Here I convert the Textblock Text into Bitmap and then assign it to the image source.
Here is how to writte a string to a bitmap:
Bitmap b = new Bitmap(200, 100);
Graphics g = Graphics.FromImage(b);
g.DrawString("My sample string", new Font("Tahoma",10), Brushes.Red, new Point(0, 0));
b.Save("mypic.png", System.Drawing.Imaging.ImageFormat.Png);
g.Dispose();
b.Dispose();
Shubhi1910 let me know if you need any details to be explained.
I've got an image upload page that works just fine when I only upload the files.
I added a 'Create Thumbnail' function. It looks like the file system has a handle on the images when the thumbnail process starts.
I get the 'unspecified GDI+ error' only when the image is over about 250K. When the files are below 250K, thumbnails are created as expected.
What are my options? Is there an elegant solution here? I want something not hacky.
Also, I am using HttpFileCollection so we can upload multiple images at one time. I've tried to use .Dispose on the Thumbnail creation, but it fails before we get to this point.
public void Upload_Click(object Sender, EventArgs e)
{
string directory = Server.MapPath(#"~\images\");
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileName = hpf.FileName;
fileName = fileName.Replace(" ", "");
hpf.SaveAs(fileName);
createThumbnail(fileName);
}
}
}
private void createThumbnail(string filename)
{
Image image = Image.FromFile(filename);
Image thumb = image.GetThumbnailImage(100,100, () => false, IntPtr.Zero);
thumb.Save(filename);
image.Dispose();
thumb.Dispose();
}
Please let me know if this works any better:
public string ImageDirectory { get { return Server.MapPath(#"~\images\"); } }
public void OnUploadClick(object sender, EventArgs e)
{
var files = HttpContext.Request.Files.AllKeys.AsEnumerable()
.Select(k =>HttpContext.Request.Files[k]);
foreach(var file in files)
{
if(file.ContentLength <= 0)
continue;
string savePath = GetFullSavePath(file);
var dimensions = new Size(100, 100);
CreateThumbnail(file,savePath,dimensions);
}
}
private void CreateThumbnail(HttpPostedFile file,string savePath, Size dimensions)
{
using (var image = Image.FromStream(file.InputStream))
{
using (var thumb = image.GetThumbnailImage(dimensions.Width, dimensions.Height, () => false, IntPtr.Zero))
{
thumb.Save(savePath);
}
}
}
private string GetFullSavePath(HttpPostedFile file)
{
string fileName = System.IO.Path.GetFileName(file.FileName).Replace(" ", "");
string savePath = System.IO.Path.Combine(this.ImageDirectory, fileName);
return savePath;
}
Edit -
The foreach should have followed more to this pattern:
var files = HttpContext.Request.Files.AllKeys.AsEnumerable()
.Select(k =>HttpContext.Request.Files[k]);
foreach(var file in files)
{
}
You can try this code to create your thumbnails.
MemoryStream ms = new MemoryStream(File.ReadAllBytes(path));
Bitmap originalBMP = new Bitmap(ms);
int maxWidth = 200;
int maxHeight = 200;
// Calculate the new image dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
double sngRatio = Convert.ToDouble(origWidth) / Convert.ToDouble(origHeight);
// New dimensions
int newWidth = 0;
int newHeight = 0;
try
{
// max 200 by 200
if ((origWidth <= maxWidth && origHeight <= maxHeight) || origWidth <= maxWidth)
{
newWidth = origWidth;
newHeight = origHeight;
}
else
{
// Width longer (shrink width)
newWidth = 200;
newHeight = Convert.ToInt32(Convert.ToDouble(newWidth) / sngRatio);
}
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.High;
// Draw the new graphic based on the resized bitmap
oGraphics.CompositingQuality = CompositingQuality.HighSpeed;
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
// Save the new graphic file to the server
EncoderParameters p = new EncoderParameters(1);
p.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 70); // Percent Compression
MemoryStream savedBmp = new MemoryStream();
newBMP.Save(savedBmp, ImageCodecInfo.GetImageEncoders()[1], p);
// Once finished with the bitmap objects, we deallocate them.
originalBMP.Dispose();
newBMP.Dispose();
oGraphics.Dispose();
savedBmp.Dispose();
Certainly a bit more work but it does give you greater control.