Why is my program not saving images? - c#

I have a program where Kinect gets a image and saves it, to a location the user specifies. I know the program finds the right folders since it creates more folders to save different kinds of images in, and those folders will be created. My current code (below) for saving the image works for other programs, so is there some parameter that is stopping it I am not aware of? Thanks in advance.
Saving the Image
using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
{
if (colorFrame == null)
{
return;
}
byte[] pixels = new byte[sensor.ColorStream.FramePixelDataLength];
//WriteableBitmap image = new WriteableBitmap(
// sensor.ColorStream.FrameWidth,
// sensor.ColorStream.FrameHeight, 96, 96,
// PixelFormats.Bgra32, null);
colorFrame.CopyPixelDataTo(pixels);
colorImage.WritePixels(new Int32Rect(0, 0, colorImage.PixelWidth,
colorImage.PixelHeight),
pixels, colorImage.PixelWidth * 4, 0);
//BitmapSource image = BitmapSource.Create(colorFrame.Width, colorFrame.Height,
// 96, 96, PixelFormats.Bgr32, null,
// pixels, colorFrame.Width * 4);
//image.WritePixels(new Int32Rect(0, 0, image.PixelWidth, image.PixelHeight),
// pixels, image.PixelWidth * sizeof(int), 0);
//video.Source = image;
totalFrames++;
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(colorImage));
//path = System.IO.Path.Combine("C:/", "Kinected", "Images");
if (PersonDetected == true)
{
if (totalFrames % 10 == 0)
{
if (file_name != null && colorImage != null)
{
try
{
using (FileStream fs = new FileStream(colorPath +
#"\Kinected Image " + time + ".jpg", FileMode.Create))
{
encoder.Save(fs);
}
}
catch (IOException)
{
System.Windows.MessageBox.Show("Save Failed");
}
}
}
skeletonDeLbl.Content = "Skeleton Detected!";
}
if (PersonDetected == false) skeletonDeLbl.Content = "No Skeleton Detected.";
}
Determining the Path
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description =
"Select which folder you want Kinected to keep all of its information/images in.";
DialogResult result = dialog.ShowDialog();
colorPath = dialog.SelectedPath + #"\Color Images";
depthPath = dialog.SelectedPath + #"\Depth Images";
facePath = dialog.SelectedPath + #"\Face Data";
if (!Directory.Exists(colorPath))
Directory.CreateDirectory(colorPath);
if (!Directory.Exists(depthPath))
Directory.CreateDirectory(depthPath);
if (!Directory.Exists(facePath))
Directory.CreateDirectory(facePath);
System.Windows.MessageBox.Show(colorPath);
EDIT
Turns out file_name was just null, but now I am getting the error when it gets to the line using (FileStream fs = new FilesStream(file_name, FileMode.Create)) it says:
An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll
Additional information: The given path's format is not supported.
Why is this happening? I am using the exact same code as Microsoft's demo, and it works fine there. Thanks.

You should use the following code to combine strings into a path
colorPath = System.IO.Path.Combine(dialog.SelectedPath, "Color Images");
The Combine method takes care of adding or removing backslashes where necessary.
And don't forget to use the debugger. You can set breakpoints and inspect the variables and do many more things.
The debugger is your best friend!
UPDATE
You are also using invalid characters in the filename. This method replaces invalid characters and applies also some other fixes to a filename
/// <summary>
/// Replaces invalid characters in a file name by " ". Apply only to the filename.ext
/// part, not to the path part.
/// </summary>
/// <param name="fileName">A file name (not containing the path part) possibly
/// containing invalid characters.</param>
/// <returns>A valid file name.</returns>
public static string GetValidFileName(string fileName)
{
string invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
string s = Regex.Replace(fileName, "[" + invalidChars + "]", " ");
s = Regex.Replace(s, #"\s\s+", " "); // Replace multiple spaces by one space.
string fil = Path.GetFileNameWithoutExtension(s).Trim().Trim('.');
string ext = Path.GetExtension(s).Trim().Trim('.');
if (ext != "") {
fil += "." + ext;
}
fil = fil.Replace(" .", ".");
return fil == "." ? "" : fil;
}

Related

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

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/

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.

Image uploading in images folder issue in Asp.net

I am trying to upload JPG file to a folder I have created in my project.
The image does not get saved in the images folder. It displays my image when I upload but the image itself is not present in images folder.
Here is the code i am using:
private void btnUpload_Click(object sender, System.EventArgs e)
{
// Initialize variables
string sSavePath;
string sThumbExtension;
int intThumbWidth;
int intThumbHeight;
// Set constant values
sSavePath = "images/";
sThumbExtension = "_thumb";
intThumbWidth = 160;
intThumbHeight = 120;
// If file field isn’t empty
if (filUpload.PostedFile != null)
{
// Check file size (mustn’t be 0)
HttpPostedFile myFile = filUpload.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
lblOutput.Text = "No file was uploaded.";
return;
}
// Check file extension (must be JPG)
if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
{
lblOutput.Text = "The file must have an extension of JPG";
return;
}
// Read file into a data stream
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData,0,nFileLen);
// Make sure a duplicate file doesn’t exist. If it does, keep on appending an
// incremental numeric until it is unique
string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ file_append.ToString() + ".jpg";
}
// Save the stream to disk
System.IO.FileStream newFile
= new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
System.IO.FileMode.Create);
newFile.Write(myData,0, myData.Length);
newFile.Close();
// Check whether the file is really a JPEG by opening it
System.Drawing.Image.GetThumbnailImageAbort myCallBack =
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap;
try
{
myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));
// If jpg file is a jpeg, create a thumbnail filename that is unique.
file_append = 0;
string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ sThumbExtension + ".jpg";
while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
{
file_append++;
sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
file_append.ToString() + sThumbExtension + ".jpg";
}
// Save thumbnail and output it onto the webpage
System.Drawing.Image myThumbnail
= myBitmap.GetThumbnailImage(intThumbWidth,
intThumbHeight, myCallBack, IntPtr.Zero);
myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile));
imgPicture.ImageUrl = sSavePath + sThumbFile;
// Displaying success information
lblOutput.Text = "File uploaded successfully!";
// Destroy objects
myThumbnail.Dispose();
myBitmap.Dispose();
}
catch (ArgumentException errArgument)
{
// The file wasn't a valid jpg file
lblOutput.Text = "The file wasn't a valid jpg file.";
System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
}
}
}
public bool ThumbnailCallback()
{
return false;
}
I'd be surprised if the line myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile)); works...
You are trying to map a file which doesn't exist yet!
Try
myThumbnail.Save(Server.MapPath(sSavePath) + sThumbFile));

Read Image file metadata

I want to upload an image file and then extract its basic information (author, dimensions, date created, modified, etc) and display it to the user. How can I do it.
A solution or reference to this problem in asp.net c# code would be helpful. But javascript or php would be ok as well.
Check this Link. You will get more Clearance about GetDetailsOf() and its File Properties based on the Win-OS version wise.
If you want to use C# code use below code to get Metadata's:
List<string> arrHeaders = new List<string>();
Shell shell = new ShellClass();
Folder rFolder = shell.NameSpace(_rootPath);
FolderItem rFiles = rFolder.ParseName(filename);
for (int i = 0; i < short.MaxValue; i++)
{
string value = rFolder.GetDetailsOf(rFiles, i).Trim();
arrHeaders.Add(value);
}
C# solution could be found here:
Link1
Link2
Bitmap image = new Bitmap(fileName);
PropertyItem[] propItems = image.PropertyItems;
foreach (PropertyItem item in propItems)
{
Console.WriteLine("iD: 0x" + item.Id.ToString("x"));
}
MSDN Reference
C# Tutorial Reference
try this...
private string doUpload()
{
// Initialize variables
string sSavePath;
sSavePath = "images/";
// Check file size (mustn’t be 0)
HttpPostedFile myFile = FileUpload1.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
//**************
//lblOutput.Text = "No file was uploaded.";
return null;
}
// Check file extension (must be JPG)
if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
{
//**************
//lblOutput.Text = "The file must have an extension of JPG";
return null;
}
// Read file into a data stream
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);
// Make sure a duplicate file doesn’t exist. If it does, keep on appending an
// incremental numeric until it is unique
string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ file_append.ToString() + ".jpg";
}
// Save the stream to disk
System.IO.FileStream newFile
= new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();
return sFilename;
}

Error while saving an image

I want to save an image after some changes in image.
but I am getting an error while calling .Save() function.
var tempapth = Server.MapPath("..//Images//Temp//" + btnfile.FileName);
btnfile.SaveAs(tempapth);
using (var fileStream = File.OpenRead(tempapth))
{
var ms = new MemoryStream();
fileStream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
System.Drawing.Image img1 = System.Drawing.Image.FromStream(ms);
fileStream.Close();
var bmp1 = img1.GetThumbnailImage(100, 150, null, IntPtr.Zero);
bmp1.Save(path);
}
bmp1.save(path);
give an error
A generic error occurred in GDI+
EDIT
The OP changed the question after I wrote this reply. Previously, there was also a path variable declared, which contained a path name (but no file name).
In the first version of your code, you had a path name without a file name (Server.MapPath("..//Images//Category//" + catid + "//");). To save, you need to add a file name, too, like:
string path = Server.MapPath("..//Images//Category//" + catid + "//Image.bmp");
The path variable contains the name of a folder, not a file.
Use something like:
bmp1.Save(Path.Combine(path, btnfile.FileName));
Side note, the character / doesn't have a special meaning in a string, it should not be escaped. Use:
var path = Server.MapPath("../Images/Category/" + catid + "/");
how about:
var srcPath = Server.MapPath("..//Images//Temp//" + btnfile.FileName);
if (!File.Exists(srcPath)
{
throw new Exception(string.Format("Could not find source file at {0}", srcPath));
}
var srcImage = Image.FromFile(srcPath);
var thumb = srcImage.GetThumbnailImage(100, 150, null, IntPtr.Zero);
var destPath = Server.MapPath("..//Images//Category//" + catid + "//");
if (!Directory.Exists(destPath))
{
Directory.CreateDirectory(destPath);
}
thumb.Save(Path.Combine(destPath, btnfile.FileName));

Categories

Resources