I have to compress the PNG file image, without losing the quality - c#

I want to compress a PNG image, to reduce its size but the quality should remain the same. I have tried to compress JPEG picture. Picture compressed about 90% and quality remain the same but when i compress a PNG image with it. No result, no compression. Same size.
Here is my code.
public const string _StatusLog = "StatusLog.csv";
static void Main(string[] args)
{
Console.WriteLine(" ### WELCOME ###");
Console.Write("\n\nPlease enter image folder path :");
string imagePath = Console.ReadLine();
Program p = new Program();
p.VaryQualityLevel(imagePath);
Console.ReadLine();
}
private void VaryQualityLevel(string pathOfImage)
{
try
{
//Console.Write("Target Directory Path :");
string targetDirectory = pathOfImage;//Console.ReadLine();
if (targetDirectory != null)
{
string[] allDirectoryInTargetDirectory = Directory.GetDirectories(targetDirectory);
//PRODUCT DIRECOTY OPEN
Console.Write("Total Folders found = " + allDirectoryInTargetDirectory.Count());
Console.Read();
if (allDirectoryInTargetDirectory.Any())
{
foreach (var directory in allDirectoryInTargetDirectory)
{
string[] subDirectory = Directory.GetDirectories(directory); // ATTRIBUTE DIRECTORY OPEN
if (subDirectory.Any())
{
foreach (var filesInSubDir in subDirectory)
{
string[] allFilesInSubDir = Directory.GetFiles(filesInSubDir);
//FILES IN SUB DIR OPEN
if (allFilesInSubDir.Any())
{
foreach (var imageFile in allFilesInSubDir)
{
try
{
Bitmap bmp1 = new Bitmap(imageFile);//pathOfImage);
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
// Create an Encoder object based on the GUID
// for the Quality parameter category.
System.Drawing.Imaging.Encoder myEncoder =
System.Drawing.Imaging.Encoder.Quality;
// Create an EncoderParameters object.
// An EncoderParameters object has an array of EncoderParameter
// objects. In this case, there is only one
// EncoderParameter object in the array.
#region SAVING THE COMPRESS IMAGE FILE
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
myEncoderParameters.Param[0] = myEncoderParameter;
bmp1.Save(filesInSubDir + "\\" + "Zip" + GettingImageNameForOptimizedImage(imageFile), jpgEncoder, myEncoderParameters);//pathOfImage
Console.WriteLine(filesInSubDir + GettingImageNameForOptimizedImage(imageFile) + " CREATED");//pathOfImage
#endregion
#region DELETING THE ORIGNAL FILE
bmp1.Dispose();
System.IO.File.Delete(filesInSubDir + "\\" + GettingImageNameForOptimizedImage(imageFile));//pathOfImage
Console.WriteLine(imageFile.Replace("jpg", "png") + " DELETED");//pathOfImage
#endregion
//myEncoderParameter = new EncoderParameter(myEncoder, 100L);
//myEncoderParameters.Param[0] = myEncoderParameter;
//bmp1.Save("D:\\" + RemovingImageFormat[0] + "100L" + ".jpg", jpgEncoder, myEncoderParameters);
#region BACK RENAMING FILE TO ORIGNAL NAME
System.IO.File.Move(filesInSubDir + "\\" + "Zip" + GettingImageNameForOptimizedImage(imageFile), filesInSubDir + "\\" + GettingImageNameForOptimizedImage(imageFile));
#endregion
}
catch (Exception ex)
{
Console.Write("\n" + ex.Message + " Press enter to continue :");
Console.ReadLine();
Console.Write("\nWould you like to retry ? [Y/N] :");
string resp = Console.ReadLine();
if (resp == "Y" || resp == "y")
{
Console.WriteLine(" -------------------\n\n");
Main(null);
}
}
}
}
}
}
}
}
}
}
catch (Exception ex)
{
Console.Write(ex);
Console.Read();
}
Console.Write("Press any key to exit...");
Console.Read();
// Get a bitmap. ###################################################################
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
public string GettingImageNameForOptimizedImage(string pathOfImage)
{
try
{
string[] splitingPathOfImage = pathOfImage.Split('\\');
string[] RemovingImageFormat = splitingPathOfImage[splitingPathOfImage.Count() - 1].ToString().Split('.');
return RemovingImageFormat[0] + ".jpg";
}
catch (Exception)
{
return null;
}
return null;
}
public static void LoggingOperations(string ImageName, string Status, bool UpdateRequired)
{
try
{
if (!File.Exists(_StatusLog))
{
using (File.Create(_StatusLog)) { }
DirectorySecurity sec = Directory.GetAccessControl(_StatusLog);
SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
Directory.SetAccessControl(_StatusLog, sec);
}
if (UpdateRequired == true)
{
string UpdateStatusText = File.ReadAllText(_StatusLog);
UpdateStatusText = UpdateStatusText.Replace(ImageName, ImageName + "," + Status);
File.WriteAllText(_StatusLog, UpdateStatusText);
UpdateStatusText = "";
}
else
{
File.AppendAllText(_StatusLog, Environment.NewLine);
File.AppendAllText(_StatusLog, Status);
}
}
catch (Exception)
{
}
}
For PNG compression i changed the following line.
Bitmap bmp1 = new Bitmap(imageFile);//pathOfImage);
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Png);
Kindly some one help me out. If there is a new method, I welcome it. If this could be altered, it would a lot better.

PNG Images are 32 bits by default. You can convert them to 8 bits : resulting file will be about 5 times smaller than the original one. With most images, the loss of quality is almost invisible.
This is what online png compressors do.
You can do this yourself by using nQuant : http://nquant.codeplex.com/ (available on Nuget)
var quantizer = new WuQuantizer();
using(var quantized = quantizer.QuantizeImage(bmp1))
{
quantized.Save(targetPath, ImageFormat.Png);
}
Full explanation of the method is available on this blog post http://www.hurryupandwait.io/blog/convert-32-bit-pngs-to-high-quality-8-bit-pngs-with-c

I also suggest looking at ImageSharp which also works with .NET Core
using (var image = Image.Load(fileData)) // fileData could be file path or byte array etc.
{
var h = image.Size().Height / 2;
var w = image.Size().Width / 2;
var options = new ResizeOptions
{
Mode = ResizeMode.Stretch,
Size = new Size(w, h)
};
image.Mutate(_ => _.Resize(options));
using (var destStream = new MemoryStream())
{
var encoder = new JpegEncoder();
image.Save(destStream, encoder);
// Do something with output stream
}
}

The one major variable in PNG compression is the tradeoff between compression speed and output size. PNG compression can actually be quite slow because it involves searching a data buffer for matching patterns. You can speed up the compression by limiting how much of the buffer the encoder searches.
Your encoder should have a setting that allows you to specify how searching for matches it will do.
IF your input PNG image was not compressed with the encoder searching the entire buffer, you may get some improved compression by searching the full buffer in your application. However, you are unlikely to get a major improvement.

PNG should be losless given pixel size and color depth are consistent.
If looking for something to baseline output size against.
https://pnggauntlet.com/

Related

Unhandled Exception: System.Net.WebException

I have a C# program that takes a URL and downloads the images off the website to the users computer.The program seems to work fine until about the 21st image and then it encounters and error(https://i.imgur.com/v8fZ77D.png). I'm not sure why this is happening.
static void Main(string[] args)
{
int num = 0;
GrantAccess("C:\\My kitty collection");
for (int i = 0; i > -1 ; i++)
{
FindSrc();
num++;
Console.WriteLine("src number" + num.ToString());
Console.WriteLine(pah);
try
{
SaveImage(pah + "\\kitty" + num.ToString() + ".jpg", ImageFormat.Jpeg, src);
}
catch (ExternalException)
{
//Something is wrong with Format -- Maybe required Format is not
// applicable here
Console.WriteLine("Error:Wrong Format");
}
catch (ArgumentNullException)
{
Console.WriteLine("Error: Stream is bad");
//Something wrong with Stream
}
}
}
//this method finds the img source
public static void FindSrc()
{
string url = "https://www.google.com/search?q=kitty&source=lnms&tbm=isch&sa=X&ved=0ahUKEwix57KhhbHjAhWSB80KHa21BL8Q_AUIECgB&biw=1920&bih=920";
WebClient client = new WebClient();
string html = code(url);
int beg = html.Substring(start).IndexOf("img height")+start;
int mid = html.Substring(beg).IndexOf("src");
int end = html.Substring(beg + mid + 5).IndexOf("\"");
src = html.Substring(beg + mid + 5, end);
start = beg + mid + 5 + end;
Console.WriteLine(src);
}
//this method downloads the image given the source, path, and format.
public static void SaveImage(string filename, ImageFormat format, string imageUrl)
{
WebClient client = new WebClient();
Stream stream = client.OpenRead(imageUrl);
Bitmap bitmap; bitmap = new Bitmap(stream);
if (bitmap != null)
bitmap.Save(filename, format);
stream.Flush();
stream.Close();
client.Dispose();
}
//this method creates a folder and give writing permissions
public static void GrantAccess(string file)
{
bool exists = System.IO.Directory.Exists(file);
if (!exists)
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(file);
pah = di.FullName;
Console.WriteLine("The Folder is created Sucessfully");
}
else
{
Console.WriteLine("The Folder already exists");
}
DirectoryInfo dInfo = new DirectoryInfo(file);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
dInfo.SetAccessControl(dSecurity);
}
}
}
I expected the program to continue to download images until it was closed, but instead it gave me the error "Unhandled Exception: System.Net.WebException"
Now You can search images with Custom image search API.
Go to - https://cse.google.com/cse/all
ref:
https://stackoverflow.com/a/34062436/6651840

Need scan through text files in a directory and filter based on loop results

I have a program that scans through text files in a directory, loops through each line and parses based on a prefix in each line. The program acts as an extractor, extracting a tif image from a Base64 string on prefix "Hxx". When the program gets the image from line "Hxx", it simply deletes the original file.
What I would like to do is keep the filtering conditions for line "TXA" but instead of converting the string on line "Hxx" to an image and deleting the file, I would like to keep the entire contents of the file. Basically, only using the program to parse and filter through the text files based on conditions for line "TXA".
I know in case "TXA" of my foreach loop, I need to save the entire file into a memory stream to re-write the file towards the end of the program. I'm just not sure how at the moment.
Any help is greatly appreciated.
/// <summary>
/// This method will open, read and parse out the image file and save it to disk.
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
static bool ParseHFPFile(string inputFileName, string outputFileName)
{
List<MemoryStream> tiffStreamList = new List<MemoryStream>();
// 1. grab file contents.
string fileContents = ProgramHelper.GetFileContents(inputFileName);
if (string.IsNullOrEmpty(fileContents))
{
return false; // errors already raised.
}
Log("[O] ", false);
// 2. split file contents into a string array.
string[] fileContentStringList = fileContents.Split('\r');
if (fileContentStringList.Length == 0)
{
Log(" ERROR: Unable to split file contents on [CR] character.");
return false;
}
// 3. loop through the file lines and parse each "section" based on it's prefix.
string mrn = string.Empty;
string dos = string.Empty;
string imgType = string.Empty;
foreach (string line in fileContentStringList)
{
if (string.IsNullOrEmpty(line))
{
continue;
}
string prefix = line.Substring(0, 3);
switch (prefix)
{
case "MSH":
break;
case "EVN":
break;
case "PID":
mrn = line.Split('|')[3].Split('^')[0];
break;
case "PV1":
dos = line.Split('|')[44];
if (!String.IsNullOrWhiteSpace(dos))
{
dos = dos.Substring(0, 8);
}
break;
case "TXA":
imgType = line.Split('|')[2].Split('^')[0];
if (imgType == "EDH02" || imgType == "EDORDH")
{
Log("[NP]");
return true;
}
break;
case "OBX":
break;
case "Hxx":
// 0 - Hxx
// 1 - page number
// 2 - image type
// 3 - base64 encoded image.
// 1. split the line sections apart based on the pipe character ("|").
string[] hxxSections = line.Split('|');
byte[] decodedImageBytes = Convert.FromBase64String(hxxSections[3].Replace(#"\.br\", ""));
// 2. create a memory stream to store the byte array.
var ms = new MemoryStream();
ms.Write(decodedImageBytes, 0, decodedImageBytes.Length);
// 3. add the memory stream to a memory stream array for later use in saving.
tiffStreamList.Add(ms);
break;
case "Z":
break;
}
}
Log("[P] ", false);
// 4. write the memory streams to a new file.
ImageCodecInfo icInfo = ImageCodecInfo.GetImageEncoders().Single(c => c.MimeType == "image/tiff");
System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag;
var ep = new EncoderParameters(1);
// 5. create references to the EncoderValues we will use
var ep1 = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
var ep2 = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);
var ep3 = new EncoderParameter(enc, (long)EncoderValue.Flush);
string newOutputFilePath = Path.GetDirectoryName(outputFileName) + #"\";
string newOutputFileName = newOutputFilePath + mrn + "_" + dos + ".dat";
bool success = false;
int suffix = 1;
while (!success)
{
if (File.Exists(newOutputFileName))
{
newOutputFileName = newOutputFilePath + mrn + "_" + dos + "_" + suffix + ".dat";
}
else
{
success = true;
}
suffix++;
}
Log(string.Format("[NewFile: {0}] ", Path.GetFileName(newOutputFileName)), false);
var strm = new FileStream(newOutputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
System.Drawing.Image pages = null;
int frame = 0;
int pageCount = tiffStreamList.Count;
Log("[WT:", false);
try
{
foreach (MemoryStream m in tiffStreamList)
{
if (frame == 0)
{
ep.Param[0] = ep1;
pages = Image.FromStream(m, false, false);
pages.Save(strm, icInfo, ep);
}
else
{
ep.Param[0] = ep2;
if (pages != null)
pages.SaveAdd(Image.FromStream(m, false, false), ep);
}
if (frame == pageCount - 1)
{
ep.Param[0] = ep3;
if (pages != null)
pages.SaveAdd(ep);
}
frame++;
Log(".", false);
//m.Close();
m.Dispose();
}
Log("]");
return true;
}
catch (Exception ex)
{
Log(" EXCEPTION: " + ex.Message + Environment.NewLine + ex.StackTrace);
return false;
}
finally
{
}
}
I'm happy that you succeeded with your task. If my comment helped you solve the problem I'm gonna post it as an answer so you can accept it if you want.
So, instead of looking for more complicated ways you can just go and create two List<string> like:
List<string> TXA = new List<string>();
List<string> FilesForDelete = new List<string>();
and then in your code, depending on what you want to do with the file:
if (fileIsTXA)
{
TXA.Add(fileName);
}
else
{
FilesForDelete.Add(fileName);
}
Later on you can use those two lists to extract the file names and do whatever you want with them.

OutOfMemoryException error in Loop

I am trying to create a Windows app which uploads files to FTP. Essentially, it looks for .jpeg files in a given folder, it reads through the barcodes found in the .jpg files before uploading it into the FTP server, and entering the URL into the database for our records.
As there will be multiple files at any given time in the folder, I am essentially trying to read them in a loop, and process them accordingly. However, I get an OutOfMemoryException whenever the loop starts again. I am trying to figure out what I'm doing wrong here. I have appended my code below:
private void btnProcess_Click(object sender, RoutedEventArgs e)
{
podPath = Directory.GetFiles(DestPath, "*.jpg");
List<string> scans = new List<string>(podPath.Length);
List<string> badscans = new List<string>();
byte[] imageBytes;
string filename, result;
POD conpod = new POD();
OTPOD otpod = new OTPOD();
ConsignmentObj scanJob;
//Pickup OTScan;
//Consolidate ccv;
for (int i = 0; i < podPath.Count(); i++ )
{
filename = podPath[i].ToString();
using (Bitmap bm = (Bitmap)Bitmap.FromFile(filename))
{
var results = barcodeReader.Decode(bm);
result = results.ToString();
bm.Dispose();
}
if (result != null)
{
//if barcode can be read, we throw the value into the database to pull out relevant information
if (result.Contains(ConNotePrefix))
{
#region Consignments
scanJob = getCon(result.ToString());
final = ImageFolder + "\\" + result.ToString() + ".jpg";
using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename))
{
MemoryStream ms = new MemoryStream();
try
{
img.Save(ms, ImageFormat.Jpeg);
imageBytes = ms.ToArray();
img.Dispose();
}
finally
{
ms.Flush();
ms.Close();
ms.Dispose();
}
}
lock (filename)
{
if (System.IO.File.Exists(filename))
{
File.Delete(filename);
}
}
using (var stream = File.Create(final)) { }
File.WriteAllBytes(final, imageBytes);
File.Delete(filename);
conpod.ConsignmentID = scanJob.ConsignmentID;
conpod.UserID = 1;
conpod.Location = ftpUrl + "//" + result.ToString() + ".jpg";
conpod.rowguid = Guid.NewGuid();
UploadFilesToFtp(ftpUrl, ftpUser, ftpPass, final, result.ToString() + ".jpg");
insertPOD(conpod);
scans.Add(result.ToString());
#endregion
}
}
else
{
badscans.Add(filename);
}
}
this.lbScans.ItemsSource = scans;
this.lbBadScans.ItemsSource = badscans;
}
The FTP method, UploadFilesToFtp(x, x, x, x, x, x) is not a problem here. All feedback will be much appreciated.
An OutOfMemoryException can also be thrown by the method FromFile of the Image class when
The file does not have a valid image format.
or
GDI+ does not support the pixel format of the file.
So i think there is a problem with one of your image files you are reading. One solution is to catch the OutOfMemoryException and adding the file to the badscans.
try{
using (Bitmap bm = (Bitmap)Bitmap.FromFile(filename)) {
var results = barcodeReader.Decode(bm);
result = results.ToString();
bm.Dispose();
}
}
catch(OutOfMemoryException) {
badscans.add(filename);
}

how to compress images with asp.net with out lose of qualityof image

I have to upload multiple images using java-script. so i need to compress those images without loose of image Quality.
I have to store all images in phyisical folder"uploads".
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++) {
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0) {
hpf.SaveAs(Server.MapPath("~/uploads/") +System.IO.Path.GetFileName(hpf.FileName));
}
}
So i need to compress the images without loose of image Quality while uploading in physical folder
I suggest converting the images to PNG and then using the built in ZIP compression.
public static void SaveToPNG(Bitmap SourceImage, string DestinationPath)
{
SourceImage.Save(DestinationPath, ImageFormat.Png);
CompressFile(DestinationPath, true);
}
private static string CompressFile(string SourceFile, bool DeleteSourceFile)
{
string TargetZipFileName = Path.ChangeExtension(SourceFile, ".zip");
using (ZipArchive archive = ZipFile.Open(TargetZipFileName, ZipArchiveMode.Create))
{
archive.CreateEntryFromFile(SourceFile, Path.GetFileName(SourceFile),CompressionLevel.Optimal);
}
if(DeleteSourceFile == true)
{
File.Delete(SourceFile);
}
return TargetZipFileName;
}
OR your if you do not mind a little unnoticable loss, then you could convert to a JPG at a high quality and then ZIP that. At 100% quality, your users will likely not notice any difference and the lower quality you go, the smaller the images will get, but that defeats your "without loss of quality" condition.
private static ImageCodecInfo __JPEGCodecInfo = null;
private static ImageCodecInfo _JPEGCodecInfo
{
get
{
if (__JPEGCodecInfo == null)
{
__JPEGCodecInfo = ImageCodecInfo.GetImageEncoders().ToList().Find(delegate (ImageCodecInfo codec) { return codec.FormatID == ImageFormat.Jpeg.Guid; });
}
return __JPEGCodecInfo;
}
}
public static void SaveToJPEG(Bitmap SourceImage, string DestinationPath, long Quality)
{
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, Quality);
SourceImage.Save(DestinationPath, _JPEGCodecInfo, parameters);
CompressFile(DestinationPath, true);
}
private static string CompressFile(string SourceFile, bool DeleteSourceFile)
{
string TargetZipFileName = Path.ChangeExtension(SourceFile, ".zip");
using (ZipArchive archive = ZipFile.Open(TargetZipFileName, ZipArchiveMode.Create))
{
archive.CreateEntryFromFile(SourceFile, Path.GetFileName(SourceFile),CompressionLevel.Optimal);
}
if(DeleteSourceFile == true)
{
File.Delete(SourceFile);
}
return TargetZipFileName;
}

Upload image, rename it, make thumbnail and replace the original. (optimization)

I have created these functions which I described in the question. However I think the way I did it is not the optimal way of doing it.
[HttpPost]
public ActionResult Create(FormCollection collection, string schooljaarparam, FlatONASAanbieder foa) {
if (ModelState.IsValid) {
// var r = new List<ViewDataUploadFilesResult>();
foreach (string file in Request.Files) {
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
//extensie nakijken. jpg, png, jpeg, of GIF.
if (MvcApplication.isImage(hpf.FileName)) {
//Image img = new Image();
string savedFileName = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory + "uploads\\ONAS\\",
Path.GetFileName(hpf.FileName));
FileInfo fi = new FileInfo(savedFileName);
int i = 1;
while (fi.Exists) {
fi = new FileInfo(savedFileName.Substring(0, savedFileName.Length - Path.GetFileName(savedFileName).Length) + Path.GetFileNameWithoutExtension(savedFileName) + " (" + i++ + ") " + Path.GetExtension(savedFileName));
}
savedFileName = fi.DirectoryName + "\\" + fi.Name;
hpf.SaveAs(savedFileName);
using (Image Img = Image.FromFile(savedFileName)) {
//Size ThumbNailSize = NewImageSize(Img.Height, Img.Width, 79);
Size NewSize = VerkleinMaxHoogte(Img.Size, 79);
using (Image ImgThnail = new Bitmap(Img, NewSize.Width, NewSize.Height)) {
//string ss = savedFileName.Substring(0, savedFileName.Length - Path.GetFileName(savedFileName).Length) + Path.GetFileNameWithoutExtension(savedFileName) + "-thumb" + Path.GetExtension(savedFileName);
ImgThnail.Save(savedFileName + ".tmp", Img.RawFormat);
ImgThnail.Dispose();
}
Img.Dispose();
}
System.IO.File.Delete(savedFileName);
FileInfo f = new FileInfo(savedFileName + ".tmp");
f.MoveTo(savedFileName);
} else {
ModelState.AddModelError("ONAS_Logo", "Het geuploadde bestand is geen afbeelding. ");
}
//r.Add(new ViewDataUploadFilesResult() {
// Name = savedFileName,
// Length = hpf.ContentLength
//});
}
}
// return View("UploadedFiles", r);
return View();
}
[NonAction]
public Size VerkleinMaxHoogte(Size orig, double height) {
double tempval = height / orig.Height;
return new Size(Convert.ToInt32(tempval * orig.Width), Convert.ToInt32(height));
}
in global.asax
public static bool isImage(string s) {
if (s.EndsWith(".jpg", true, null) || s.EndsWith(".jpeg", true, null) || s.EndsWith(".gif", true, null) || s.EndsWith(".png", true, null)) {
return true;
}
return false;
}
so the way I do it:
I get the file from the browser
I check if it is an Image
I check if the file exists, and if so, change the filename accordingly
I save the file on disk (IO, slow)
I open the file as an image
I calculate the width and height with the VerkleinMaxHoogte method
I create the thumbnail and save it with a tmp extension
I delete the original file
I rename the thumbnail to the original file name (this is what I want)
How do I do it faster?
You can always use HttpPostedFile.InputStream and Image.FromStream method to combine #4 & #5. This will also eliminate #8 & #9.

Categories

Resources