I get an Invalid Parameter error when calling the System.Drawing.Image.Save function. i google and found some suggestions but nothing works. what I'm trying to do is that when I upload an image, and if it is lager than 100kb, I would like to reduce the image size to half. please, help.
System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(realpath); FullsizeImage = System.Drawing.Image.FromFile(realpath); int fileSize = (int)new System.IO.FileInfo(realpath).Length; while (fileSize > 100000) //If Larger than 100KB { SaveJpeg(realpath, FullsizeImage); fileSize = (int)new System.IO.FileInfo(realpath).Length; } private static ImageCodecInfo GetEncoderInfo(string mimeType) { // Get image codecs for all image formats ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); // Find the correct image codec for (int i = 0; i < codecs.Length; i++) if (codecs[i].MimeType == mimeType) return codecs[i]; return null; } public static void SaveJpeg(string path, Image img) { Image NewImage = img; img.Dispose(); EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, 85L); EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; ImageCodecInfo jpegCodec = GetEncoderInfo(GetMimeType(path.Substring(path.LastIndexOf('.'), path.Length - path.LastIndexOf('.')))); //THE ERROR IS HERE!!!!!! NewImage.Save(path, jpegCodec, encoderParams); //THE ERROR IS HERE!!!!!! } public static string GetMimeType(string extension) { if (extension == null) { throw new ArgumentNullException("extension"); } if (!extension.StartsWith(".")) { extension = "." + extension; } switch (extension.ToLower()) {
EDIT: I changed the code as shown below, now the image is saved without any exceptions! Thank you but another problem here. file size is not reduced. which means my while loop can never exit. please help and thanks again.
using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(realpath))) { using (Image FullsizeImage = Image.FromStream(ms)) { //code here int fileSize = (int)new System.IO.FileInfo(realpath).Length; while (fileSize > 100000) //If Larger than 100KB { SaveJpeg(realpath, FullsizeImage, 85L); fileSize = (int)new System.IO.FileInfo(realpath).Length; } } }
Can someone help me, my problem is not solved yet :(
source share