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));
Related
I thought that should be simple, yet I can't figure it out.
I keep getting the error: System.IO.DirectoryNotFoundException: Could not find a part of the path "/storage/emulated/0/Pictures/Screenshots/name.jpg".
The code:
string root = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).Path;
File myDir = new File(root + "/Screenshots");
myDir.Mkdirs();
string timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Date());
string fname = CommunicationHandler.GetNickname() + "|" + timeStamp + ".jpg";
File file = new File(myDir, fname);
if (file.Exists())
file.Delete();
try
{
using (System.IO.Stream outStream = System.IO.File.Create(file.Path))
{
finalBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, outStream);
outStream.Flush();
outStream.Close();
}
}
catch (Exception e)
{
Toast.MakeText(Activity, e.ToString(), ToastLength.Long).Show();
}
Also, I can't access manually to /storage/emulated/0..
Why can't I manage to save the bitmap to my phone gallery? What's the problem in the code above?
If you want to create a new directory, you can use System.IO.Directory.CreateDirectory(root); to create it.
//create a directory called MyCamera
string root = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim).ToString() + "/MyCamera/";
//create the Directory
System.IO.Directory.CreateDirectory(root);
As taken from here:
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
Also, note that you could just add an image to the gallery via a simple line:
MediaStore.Images.Media.insertImage(applicationContext.getContentResolver(), IMAGE ,"nameofimage" , "description");
I have to save an image in post request in byte64String format
when i save that image i get A generic error occurred in GDI+
here is my code
byte[] ix = Convert.FromBase64String(obj.Image);
var ID = obj.Id;
using (var mStream = new MemoryStream(ix))
{
var img = Image.FromStream(mStream);
var image = obj.ImageName + ".jpg";
string path = HostingEnvironment.MapPath("/Images/" + ImageType + "/" + ID + "/" + image);
System.IO.Directory.CreateDirectory(path);
try
{
img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception e)
{
var d = e;
}
}
also
this is not a permission issue as i am able to create text files in the same directory
Quite simply you are confusing paths and filenames.
The problem if could hazzard a guess, you probably have a folder that is your filename, and you are trying to save a file with that same name, which windows forbids
Your code tweaked
var image = $"{obj.ImageName }.jpg";
// get the path, and only the path
string path = HostingEnvironment.MapPath($"/Images/{ImageType}/{ID}/");
// Create directory if needed (from that path)
Directory.CreateDirectory(path,image);
...
// now create the correct full path
var fullPath = Path.Combine(path,fileName);
// save
img.Save(fullPath, ImageFormat.Jpeg);
After using the File.Copy function to copy a text file from one location to another i try the exact same functionality (that i've already gotten to work) on another text file fails to write. However, the weird part is that there is NO EXCEPTION thrown! I know the file exists by doing
if(File.Exist(myFile))
My File.Copy code:
File.Copy(sourceFilePathCombined, targetFilePathCombined, true);
This works well for one file in the same directory, but not for the other. There is NO exception. Why won't it write the file, but the other file gets copied without issue?
Code for those who need it:
var indexFileDirectory = ConfigurationManager.AppSettings["Accident.IndexFileDirectory"];
var xRefToDoList = ConfigurationManager.AppSettings["Accident.XRefToDoList"];
var xRefToDoResult = ConfigurationManager.AppSettings["Accident.XRefToDoResult"];
var toDoFilePath = Path.Combine(indexFileDirectory, xRefToDoResult);
var indexFilePath = Path.Combine(indexFileDirectory , xRefToDoList);
//Includes date-time stamp to suffix the file
var xRefToDoResultsDateTime = DateTime.Now.ToString("yyMMddhhmmss");
//If the directory does not exist then create it
if (!Directory.Exists(XRefPath))
{
Directory.CreateDirectory(XRefPath);
}
var indexToStart = xRefToDoList.IndexOf(".");
var test2 = xRefToDoList.Remove(indexToStart, 4);
indexToStart = xRefToDoResult.IndexOf(".");
var test3 = xRefToDoResult.Remove(indexToStart, 8);
var xRefToDoListCombinedPath = Path.Combine(XRefPath, (test2 + "_lst" + "." + xRefToDoResultsDateTime));
var xRefResultListCombinedPath = Path.Combine(XRefPath, (test3 + "_results" + "." + xRefToDoResultsDateTime));
string extension = Path.GetExtension(toDoFilePath);
try
{
File.Copy(indexFilePath, xRefToDoListCombinedPath, true);//THIS WORKS!
File.Copy(toDoFilePath, xRefResultListCombinedPath, true);//this does NOT
}
catch (Exception ex)
{
var test = ex;
}
Try using foreach to move all files
if (!System.IO.Directory.Exists(targetPath))
System.IO.Directory.CreateDirectory(targetPath);
string[] files = Directory.GetFiles(sourcePath);
foreach (var file in files)
{
string name = Path.GetFileName(file);
string target = Path.Combine(targetPath, name);
File.Copy(file, target, true);
}
Be sure to not confuse Date Modified with Date Created when looking for the file in a directory. It may look like it didn't get created if it has a Date Modified value.
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;
}
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;
}