BitmapFrame.Create fails with escaped characters in Uri - c#

I am using WPF/C# in VS2017.
My code takes a path to an image file as a string and tries to load it into a BitmapFrame, which has worked fine mostly, except someone tested it with some image files from a Mac and it threw an exception. It turns out that the filename contains the character #F025, which in Windows is just displayed as a thick dot.
The files are photos, named from the photograph title. This one had a question mark in it, but ended up with #F025.
Anyway, the code converts the string to a Uri and then uses BitmapFrame as follows:
public new void Init()
{
Source = new Uri(Path);
fi = new FileInfo(Path);
BitmapImage bs;
try
{
Image = BitmapFrame.Create(Source);
Metadata = new ExifMetadata(Image);
}
catch (Exception e)
{
Error = e.Message;
IsBroken = true;
}
When I look at the Uri "Source" in the debugger, then #F025 character has been replaced with "%25EF%2580%25A5". The Create function throws a "File Not Found" exception.
If there any way of converting this to a Uri that the Create function will accept, or perhaps just using the string Path to load it instead? I did try using a stream with the filename but that didn't work either.
TIA.

You may try to create the BitmapFrame from a FileStream. Note that BitmapCacheOption.OnLoad must be set in order to be able to close the stream immediately after the Create call.
using (var stream = File.OpenRead(Path))
{
Image = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}

Related

Is there a function that takes a filename from the Image object

I'm using the Movie Maker Library Timeline SDK Control 6.0 dll
And to add a photo you need a STRING of a file name. So far everything is fine
But I want to insert a function that gets an IMAGE object
But the library does not have a function that cables an IMAGE object
What I need is to get the file name out of the IMAGE object
That is: string fileName = image
Image img = default;
using (WebClient client = new WebClient())
{
string url = textBox1.Text;
Stream stream = client.OpenRead(url);
img = Image.FromStream(stream);
axTimelineControl1.AddImageClip(trackIndex: 1, fileName :img.ToString(),
clipStartTime: axTimelineControl1.GetMediaDuration(img.ToString()), clipStopTime: 4);
}
You've got a small bit of an "XY problem" here--you're asking the wrong question. Your axTimelineControl1 expects an image's file name. This implies that it also expects there to be an image saved to disk with that file name.
But all you have is a remote image, behind some URL. client.OpenRead(url) downloads the image into a Stream, but you can't do anything with that directly.
So, you don't want to take that image, and put it into a WinForms Image object. Instead, you want to save that image to disk with a file name, and then give that file name to your axTimelineControl1.
You have a few options for doing that:
1) You could take the Stream you got from client.OpenRead(), turn it into a FileStream and save it to disk.
2) You could use the WebClient to download the image directly to disk, and then give the image's file name to the axTimelineControl1.
Let's do 2) instead. It'll save a few steps.
First, create the file.
string fileName = System.IO.Path.GetTempFileName();
System.IO.File.Create(fileName).Close();
We're creating a "Temp" file here--these are meant to be treated as disposable. Note that Windows doesn't clean them up for you, so once you're done with it, your program should delete it. System.IO.File.Create() gives us a FileStream object, but we don't need it, so we Close() it right away, so that the WebClient will be able to write to our file.
Next, we download our image, and tell WebClient to save it to our newly-created Temp file:
// Defining my own URL here. Feel free to substitute your own.
string url = "https://derpicdn.net/img/view/2018/5/18/1735426.jpeg";
using (var client = new WebClient())
{
client.DownloadFile(url, fileName);
}
Now we have an image on disk, and we can tell the Movie Maker SDK Control where to find it:
float duration = axTimelineControl1.GetMediaDuration(fileName);
axTimelineControl1.AddImageClip(
trackIndex: 1,
fileName: fileName,
clipStartTime: duration,
clipStopTime: 4);
And that should do it.
The entire code listing:
string fileName = System.IO.Path.GetTempFileName();
System.IO.File.Create(fileName).Close();
// Defining my own URL here. Feel free to substitute your own.
string url = "https://derpicdn.net/img/view/2018/5/18/1735426.jpeg";
using (var client = new WebClient())
{
client.DownloadFile(url, fileName);
}
float duration = axTimelineControl1.GetMediaDuration(fileName);
axTimelineControl1.AddImageClip(
trackIndex: 1,
fileName: fileName,
clipStartTime: duration,
clipStopTime: 4);
Don't forget to clean up your temp file!

Issue serializing new bitmap image in xml file [duplicate]

i've got some binary data which i want to save as an image. When i try to save the image, it throws an exception if the memory stream used to create the image, was closed before the save. The reason i do this is because i'm dynamically creating images and as such .. i need to use a memory stream.
this is the code:
[TestMethod]
public void TestMethod1()
{
// Grab the binary data.
byte[] data = File.ReadAllBytes("Chick.jpg");
// Read in the data but do not close, before using the stream.
Stream originalBinaryDataStream = new MemoryStream(data);
Bitmap image = new Bitmap(originalBinaryDataStream);
image.Save(#"c:\test.jpg");
originalBinaryDataStream.Dispose();
// Now lets use a nice dispose, etc...
Bitmap2 image2;
using (Stream originalBinaryDataStream2 = new MemoryStream(data))
{
image2 = new Bitmap(originalBinaryDataStream2);
}
image2.Save(#"C:\temp\pewpew.jpg"); // This throws the GDI+ exception.
}
Does anyone have any suggestions to how i could save an image with the stream closed? I cannot rely on the developers to remember to close the stream after the image is saved. In fact, the developer would have NO IDEA that the image was generated using a memory stream (because it happens in some other code, elsewhere).
I'm really confused :(
As it's a MemoryStream, you really don't need to close the stream - nothing bad will happen if you don't, although obviously it's good practice to dispose anything that's disposable anyway. (See this question for more on this.)
However, you should be disposing the Bitmap - and that will close the stream for you. Basically once you give the Bitmap constructor a stream, it "owns" the stream and you shouldn't close it. As the docs for that constructor say:
You must keep the stream open for the
lifetime of the Bitmap.
I can't find any docs promising to close the stream when you dispose the bitmap, but you should be able to verify that fairly easily.
A generic error occurred in GDI+.
May also result from incorrect save path!
Took me half a day to notice that.
So make sure that you have double checked the path to save the image as well.
Perhaps it is worth mentioning that if the C:\Temp directory does not exist, it will also throw this exception even if your stream is still existent.
Copy the Bitmap. You have to keep the stream open for the lifetime of the bitmap.
When drawing an image: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI
public static Image ToImage(this byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
using (var image = Image.FromStream(stream, false, true))
{
return new Bitmap(image);
}
}
[Test]
public void ShouldCreateImageThatCanBeSavedWithoutOpenStream()
{
var imageBytes = File.ReadAllBytes("bitmap.bmp");
var image = imageBytes.ToImage();
image.Save("output.bmp");
}
I had the same problem but actually the cause was that the application didn't have permission to save files on C. When I changed to "D:\.." the picture has been saved.
You can try to create another copy of bitmap:
using (var memoryStream = new MemoryStream())
{
// write to memory stream here
memoryStream.Position = 0;
using (var bitmap = new Bitmap(memoryStream))
{
var bitmap2 = new Bitmap(bitmap);
return bitmap2;
}
}
This error occurred to me when I was trying from Citrix. The image folder was set to C:\ in the server, for which I do not have privilege. Once the image folder was moved to a shared drive, the error was gone.
A generic error occurred in GDI+. It can occur because of image storing paths issues,I got this error because my storing path is too long, I fixed this by first storing the image in a shortest path and move it to the correct location with long path handling techniques.
I was getting this error, because the automated test I was executing, was trying to store snapshots into a folder that didn't exist. After I created the folder, the error resolved
One strange solution which made my code to work.
Open the image in paint and save it as a new file with same format(.jpg). Now try with this new file and it works. It clearly explains you that the file might be corrupted in someway.
This can help only if your code has every other bugs fixed
It has also appeared with me when I was trying to save an image into path
C:\Program Files (x86)\some_directory
and the .exe wasn't executed to run as administrator, I hope this may help someone who has same issue too.
For me the code below crashed with A generic error occurred in GDI+on the line which Saves to a MemoryStream. The code was running on a web server and I resolved it by stopping and starting the Application Pool that was running the site.
Must have been some internal error in GDI+
private static string GetThumbnailImageAsBase64String(string path)
{
if (path == null || !File.Exists(path))
{
var log = ContainerResolver.Container.GetInstance<ILog>();
log.Info($"No file was found at path: {path}");
return null;
}
var width = LibraryItemFileSettings.Instance.ThumbnailImageWidth;
using (var image = Image.FromFile(path))
{
using (var thumbnail = image.GetThumbnailImage(width, width * image.Height / image.Width, null, IntPtr.Zero))
{
using (var memoryStream = new MemoryStream())
{
thumbnail.Save(memoryStream, ImageFormat.Png); // <= crash here
var bytes = new byte[memoryStream.Length];
memoryStream.Position = 0;
memoryStream.Read(bytes, 0, bytes.Length);
return Convert.ToBase64String(bytes, 0, bytes.Length);
}
}
}
}
I came across this error when I was trying a simple image editing in a WPF app.
Setting an Image element's Source to the bitmap prevents file saving.
Even setting Source=null doesn't seem to release the file.
Now I just never use the image as the Source of Image element, so I can overwrite after editing!
EDIT
After hearing about the CacheOption property(Thanks to #Nyerguds) I found the solution:
So instead of using the Bitmap constructor I must set the Uri after setting CacheOption BitmapCacheOption.OnLoad.(Image1 below is the Wpf Image element)
Instead of
Image1.Source = new BitmapImage(new Uri(filepath));
Use:
var image = new BitmapImage();
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(filepath);
image.EndInit();
Image1.Source = image;
See this: WPF Image Caching
Try this code:
static void Main(string[] args)
{
byte[] data = null;
string fullPath = #"c:\testimage.jpg";
using (MemoryStream ms = new MemoryStream())
using (Bitmap tmp = (Bitmap)Bitmap.FromFile(fullPath))
using (Bitmap bm = new Bitmap(tmp))
{
bm.SetResolution(96, 96);
using (EncoderParameters eps = new EncoderParameters(1))
{
eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bm.Save(ms, GetEncoderInfo("image/jpeg"), eps);
}
data = ms.ToArray();
}
File.WriteAllBytes(fullPath, data);
}
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; ++j)
{
if (String.Equals(encoders[j].MimeType, mimeType, StringComparison.InvariantCultureIgnoreCase))
return encoders[j];
}
return null;
}
I used imageprocessor to resize images and one day I got "A generic error occurred in GDI+" exception.
After looked up a while I tried to recycle the application pool and bingo it works. So I note it here, hope it help ;)
Cheers
I was getting this error today on a server when the same code worked fine locally and on our DEV server but not on PRODUCTION. Rebooting the server resolved it.
public static byte[] SetImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
public static Bitmap SetByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
return bm;
}

Xamarin Android, read a simple text file from internal storage/Download

I'm using Xamarin, and according to previous answers, this shall work:
string path = Path.Combine(Android.OS.Environment.DirectoryDownloads, "families.txt");
File.WriteAllText(path, "Write this text into a file!");
But it doesn't, I get and unhandled exception. I have set the permissions to read and write to external storage (even though this is internal).
I also tried it with this:
string content;
using (var streamReader = new StreamReader(#"file://" + path )) // with and without file://
{
content = streamReader.ReadToEnd();
}
But I got the same unhandled exception.
UPDATE: The path is the problem, since I get the else part here:
Java.IO.File file = new Java.IO.File(path);
if (file.CanRead())
testText.Text = "The file is there";
else
testText.Text = "The file is NOT there\n" + path;
Which is weird, because the path seems to be correct. The exceptions: Could not find a part of the path: /Download/families.txt
UPDATE2: On external storage, it works, with the same code... Might it be my device's problem? That would be great, cause I tested the external storage version on my friend's phone, but mine doesn't have external storage (OnePlus One), so I'm still looking for a solution (if there's any).
Finally found a solution.
var path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filename = Path.Combine(path.ToString(), "myfile.txt");
The path was the problem, now with a simple streamwriter it works like magic.
try
{
using (var streamWriter = new StreamWriter(filename, true))
{
streamWriter.WriteLine("I am working!");
}
}
catch { ... }

My stream keeps throwing Read/Write Timeout exceptions

I am parsing a PowerPoint presentation using Open Office SDK 2.0. At one point in the program I'm passing a stream to a method that will return an image's MD5. However, there seems to be a problem in the stream, before it even gets to my MD5 method.
Here's my code:
// Get image information here.
var blipRelId = blip.Embed;
var imagePart = (ImagePart)slidePart.GetPartById(blipRelId);
var imageFileName = imagePart.Uri.OriginalString;
var imageStream = imagePart.GetStream();
var imageMd5 = Hasher.CalculateStreamHash(imageStream);
In debug, before I let it drop into Hasher.CalculateStreamHash, I check the imageStream properties. Immediately, I see that the ReadTimeout and WriteTimeout both have similar errors:
imageStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException
imageStream.WriteTimeout' threw an exception of type 'System.InvalidOperationException
Here's a picture of the properties that I"m seeing during debug, in case it helps:
This code is running over a PowerPoint presentation. I'm wondering if the fact that it's zipped (a PowerPoint presentation is basically just a zipped up file) is the reason I'm seeing those timeout errors?
UPDATE: I tried taking the stream, getting the image and converting it to a byte array and sending that to the MD5 method as a memory stream, but I still get those same errors in the Read/Write Timeout properties of the stream. Here's the code as it is now:
// Get image information here.
var blipRelId = blip.Embed;
var imagePart = (ImagePart)slidePart.GetPartById(blipRelId);
var imageFileName = imagePart.Uri.OriginalString;
var imageStream = imagePart.GetStream();
// Convert image to memory stream
var img = Image.FromStream(imageStream);
var imageMemoryStream = new MemoryStream(this.imageToByteArray(img));
var imageMd5 = Hasher.CalculateStreamHash(imageMemoryStream);
For clarity, here's the signature for the CalculateStreamHash method:
public static string CalculateStreamHash([NotNull] Stream stream)
Mischief managed! I was able to overcome this problem by using a BufferedStream and adding an overloaded method to my MD5 method that accepted a BufferedStream as a parameter:
// Get image information here.
var blipRelId = blip.Embed;
var imagePart = (ImagePart)slidePart.GetPartById(blipRelId);
var imageFileName = imagePart.Uri.OriginalString;
// Convert image to buffered stream
var imageBufferedStream = new BufferedStream(imagePart.GetStream());
var imageMd5 = Hasher.CalculateStreamHash(imageBufferedStream);
...and:
public static string CalculateStreamHash([NotNull] BufferedStream bufferedStream)

C# Save image without using Dialog

I am having trouble saving a user uploaded image to my "logos" file when the user presses "Save Team" on my form.
For you to get a taster of what the application does I have provided a screenshot here, upon pressing add team all the text box data is written to a text file and I want the image to automatically save into a predefined folder "logos", however I get the GDI++ error whenever I press save.
After reading through a few old threads on the web, I found that it could be caused by a few things such as file permissions, file size, the files name or even an open stream.
Below is the code I am currently using to save out my file which prompts the error:
private void btnAddTeam_Click(object sender, EventArgs e)
{
//VALIDATION FOR TEXT FILE AND OTHER STUFF HERE...
//SAVE THE IMAGE FILE
string filePath = picTeamLogo.ImageLocation;
Image tempImage = Image.FromFile(filePath);
tempImage.Save(#"../logos/");
}
If you are viewing the screenshot, please do not get confused by "arsenal.png" I am aware that that is not the full file path, its conversion is handled in another method, as only the filename is required to be written to the text file.
If anybody has any ideas on where I am going wrong then please point me in the right direction, vague errors such as the GDI one I just received are such a headache!
Alex.
Try this method
public void storeFile(FileUpload File, string dirName)
{
if (!Directory.Exists(MapPath("~/uploads/" + dirName)))
{
Directory.CreateDirectory(MapPath("~/uploads/" + dirName));
}
string saveLocation = MapPath("~/uploads/" + dirName + "/" + Path.GetFileName(File.FileName));
File.SaveAs(saveLocation);
}
that's because you have not specified the file name for save function !
take a look at this :
string filePath = picTeamLogo.ImageLocation;
FileInfo fi = new FileInfo(filePath);
Image tempImage = Image.FromFile(fi.FullName);
tempImage.Save(#"../logo/" + fi.Name);
now it works properly
See this earlier post of mine for similar issue...
A Generic error occurred in GDI+ in Bitmap.Save method
The stream remains locked - you can use memory stream as a temp location then save.
When either a Bitmap object or an Image object is constructed from a
file, the file remains locked for the lifetime of the object. As a
result, you cannot change an image and save it back to the same file
where it originated.
http://support.microsoft.com/?id=814675
string outputFileName = "...";
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
{
tempImage.Save(memory, ImageFormat.Jpeg);
// memory.ToStream(fs) // I think the same
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
Or alternative is loading image via MemoryStream into the image - so the stream doesn't get locked in the first place...

Categories