I serialize images using the following code:
public static string SerializeImage(Image image)
{
using (MemoryStream memoryStream = new MemoryStream())
{
image.Save(memoryStream, image.RawFormat);
return Convert.ToBase64String(memoryStream.ToArray());
}
}
and deserialize the images by doing the following
public static Image DeserializeImage(string serializedImage)
{
byte[] imageAsBytes = Convert.FromBase64String(serializedImage);
using (MemoryStream memoryStream = new MemoryStream(imageAsBytes, 0, imageAsBytes.Length))
{
memoryStream.Write(imageAsBytes, 0, imageAsBytes.Length);
return Image.FromStream(memoryStream, true);
}
}
If I have an image and does
string serializedImage1 = SerializeImage(image);
Image deserializedImage = DeserializeImage(serializedImage1);
string serializedImage2 = SerializeImage(deserializedImage );
Then
serializedImage1 == serializedImage2;
as expected. But it is not always the case.
If I serialize an image on Process 1, and then redeserialize and reserialize it on Process 2, then the result of the reserialization on Process 2 is not the same as on the Process 1. Everything works, but a few bytes in the beginning of the serialization are different.
Worst, if I do the same thing on 2 different dll (or thread, I'm not sure), it seems the serialization result is not the same too. Again, the serialization/deserialization works, but a few bytes are different.
The image the first time is loaded with the following function :
public static Image GetImageFromFilePath(string filePath)
{
var uri = new Uri(filePath);
var bitmapImage = new BitmapImage(uri);
bitmapImage.Freeze();
using (var memoryStream = new MemoryStream())
{
var pngBitmapEncoder = new PngBitmapEncoder();
pngBitmapEncoder.Frames.Add(BitmapFrame.Create(bitmapImage));
pngBitmapEncoder.Save(memoryStream);
Image image = Image.FromStream(memoryStream);
return image;
}
}
Note however that it happens even if the image is loaded twice with the DeserializeImage() function.
The tests I have done are with ImageFormat.Jpeg and ImageFormat.Png.
First question, why it does this ? I would have expected the result to be always the same, but I suppose some salt is used when doing the Image.Save().
Second question : I want to have a deterministic way to serialize an image, keeping the image format intact. The goal is to save the image in a DB and also to compare serialized images to know if it already exists in the system where this function is used.
Well, I discovered while trying to solve this that a png or jpeg Image object inside C# has some metadata associated to it and doing what I was doing is just not a reliable way to compare images.
The solution I used was derived from this link
https://insertcode.wordpress.com/2014/05/13/compare-content-of-two-files-images-in-c/
So what I do finally is save the images inside the system with the SerializeImage(Image image) function previously described, and when I want to consume it I deserialize it with the DeserializeImage(string serializedImage) function previously described. But when I want to compare images I use the following functions
public static bool ImagesAreEqual(Image image1, Image image2)
{
string image1Base64Bitmap = GetImageAsBase64Bitmap(image1);
string image2Base64Bitmap = GetImageAsBase64Bitmap(image2);
return image1Base64Bitmap.Equals(image2Base64Bitmap);
}
public static string GetImageAsBase64Bitmap(Image image)
{
using (var memoryStream = new MemoryStream())
{
using (var bitmap = new Bitmap(image))
{
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
}
return Convert.ToBase64String(memoryStream.ToArray());
}
}
That convert the image to raw bitmap before comparing them.
This does a perfect job for me in all my needed cases : the formats of the images are saved/restored correctly, and I can compare them between them to check if they are the same without having to bother with the possibly different serialization.
I have to "generate" a png file and send it to the Telegram bot via SendPhotoAsync of SeendDocumentAsync.
This is a piece of my C# code:
...
Bitmap speedometer = new Bitmap(#"C:\Immagini\bot\speedometer.png");
Bitmap pointer = new Bitmap(#"C:\Immagini\bot\pointer.png");
Bitmap finalImage = new Bitmap(speedometer);
using (Graphics graphics = Graphics.FromImage(finalImage))
{
Bitmap rotatedPointer = RotateImage(pointer, efficienza_int * (float)1.8);
rotatedPointer.MakeTransparent(Color.White);
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.DrawImage(rotatedPointer, 0, 0);
?????????????
}
Now, I want to send my finalImage without saving it on the disk with Save method.
How can I?
Thanks in advice!
Save it to MemoryStream, and send the MemoryStream in your call to the bot, like this:
using (MemoryStream ms = new MemoryStream())
using (Bitmap finalImage = new Bitmap(speedometer))
{
using (Graphics graphics = Graphics.FromImage(finalImage))
{
// ... stuff
}
finalImage.Save(ms, ImageFormat.Png);
// This is important: otherwise anything reading the stream
// will start at the point AFTER the written image.
ms.Position = 0;
Bot.SendPhotoAsync(/* send 'ms' here. Whatever the exact args are */);
}
It is possible that async sending requires the stream to remain open. Though, normally, when you have such an async send, you can specify a function that should be called after the sending has finished.
In that case, you should not put the MemoryStream in a using block, but instead store the stream object in a global variable in your class, and make sure that the function handling the end of the async send disposes it.
Also do note this question...
bot.sendphoto does not work asp.net
Apparently SendPhotoAsync is not enough to actually send it; the answer there specifies you need to call .GetAwaiter() and .GetResult(). I don't know the API, so you'll have to figure that out yourself.
From the Telegram Bot API documentation (link)
Sending files
There are three ways to send files (photos, stickers, audio, media, etc.):
...
Post the file using multipart/form-data in the usual way that files are uploaded via the browser. 10 MB max size for photos, 50 MB for other files.
Your question is not clear!
However, (if I understand your question right)
You are using TelgramBotClient from this repository: https://github.com/TelegramBots
when you invoke SendPhotoAsync from this client it takes FileToSend as a parameter which represent the photo you processed with rotation, transparency and smoothing.
when you pass this FileToSend you can set the photo either by loading it from temp file you created after processing or you can load it directory from MemoryStream like this:
using System.Drawing;
using System.Drawing.Drawing2D;
using Telegram.Bot;
using Telegram.Bot.Args;
using System.IO;
using System.Drawing.Imaging;
namespace LoadGraphicsFromMemory
{
public static class ImageExtensions
{
public static MemoryStream ToMemoryStream(this Bitmap image, ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, format);
return ms;
}
}
}
class Program
{
private static float efficienza_int;
private static readonly TelegramBotClient Bot = new TelegramBotClient("Your API key");
static void Main(string[] args)
{
Bot.OnMessage += BotOnMessageReceived;
}
private static void BotOnMessageReceived(object sender, MessageEventArgs e)
{
Bitmap speedometer = new Bitmap(#"C:\Immagini\bot\speedometer.png");
Bitmap pointer = new Bitmap(#"C:\Immagini\bot\pointer.png");
Bitmap finalImage = new Bitmap(speedometer);
using (Graphics graphics = Graphics.FromImage(finalImage))
{
Bitmap rotatedPointer = RotateImage(pointer, efficienza_int * (float)1.8);
rotatedPointer.MakeTransparent(Color.White);
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.DrawImage(rotatedPointer, 0, 0);
}
Bot.SendPhotoAsync(e.Message.Chat.Id, new Telegram.Bot.Types.FileToSend("My File", finalImage.ToMemoryStream(ImageFormat.Jpeg)));
}
private static Bitmap RotateImage(Bitmap pointer, object p)
{
return pointer;
}
}
}
I have a function that add an Image file to stream like this:
//sourceImage is a url for an image
public Stream AddImageToStream(string sourceImage)
{
try
{
using (WebClient webClient = new WebClient())
{
byte[] data = webClient.DownloadData(sourceImage);
using (MemoryStream mem = new MemoryStream(data))
{
using (var yourImage = Image.FromStream(mem))
{
Image img = yourImage;
var ms = img.ToStream(ImageFormat.Png);
img.Dispose();
return ms;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
I can't find Video class in C#.
How can implement this function for video files?
Basically you already know how to turn the downloaded content into a MemoryStream:
public Stream DownloadToStream(string url)
{
using (var webClient = new System.Net.WebClient())
{
byte[] data = webClient.DownloadData(url);
var ms = new System.IO.MemoryStream(data);
return ms;
}
}
But this will need the video or whatever to fit into memory, there is no progress handling and nothing asynchronous. Also you should Dispose() the returned stream when you finished your operations with it.
There is no Video class in the basic .NET framework as videos are a complex topic. If you want to process it, you should look into some of the frameworks/libraries for that and definitely have to learn about asynchronous processing and streams.
Update: If you can use current versions of the framework you might be interested in using HttpClient.GetStreamAsync. This will not consume all your memory. Still if you want to edit the video data you will require a framework specialized on video editing.
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;
}
It's definitely possible to convert an SVG to EMF, for example this website. I wonder if it's possible to achieve this conversion in C#?
Update:
I tried to read an SVG file using SVG.NET and draw it to a Graphics object, then tried export the Image as a MetaFile in .emf extension (I followed the instruction here: GDI+ / C#: How to save an image as EMF?). The reading was done successfully and the image did get exported as .emf. However, when I opened that .emf in PowerPoint, it couldn't be un-grouped, which indicated that the drawing info of that file was actually not dumped correctly.
Update 2:
Now it does export a ungroup-able .emf, but the ungrouping shows a really poor result. I used the following code to produce the .emf:
private void OpenPictureButtonClick(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
_svgDoc = SvgDocument.Open(openFileDialog.FileName);
RenderSvg(_svgDoc);
}
private void SavePictureClick(object sender, EventArgs e)
{
var saveFileDialog = new SaveFileDialog {Filter = "Enhanced Meta File | *.Emf"};
saveFileDialog.ShowDialog();
var path = saveFileDialog.FileName;
var graphics = CreateGraphics();
var img = new Metafile(path, graphics.GetHdc());
var ig = Graphics.FromImage(img);
_svgDoc.Draw(ig);
ig.Dispose(); img.Dispose(); graphics.ReleaseHdc(); graphics.Dispose();
}
private void RenderSvg(SvgDocument svgDoc)
{
svgImageBox.Image = svgDoc.Draw();
}
I had the same issue but searching had no results.
Finally I ended up with my own simple solution below. I used SVG.NET.
public static byte[] ConvertToEmf(string svgImage)
{
string emfTempPath = Path.GetTempFileName();
try
{
var svg = SvgDocument.FromSvg<SvgDocument>(svgImage);
using (Graphics bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
{
using (var metafile = new Metafile(emfTempPath, bufferGraphics.GetHdc()))
{
using (Graphics graphics = Graphics.FromImage(metafile))
{
svg.Draw(graphics);
}
}
}
return File.ReadAllBytes(emfTempPath);
}
finally
{
File.Delete(emfTempPath);
}
}
At first I create a temp file. Then I use Draw(Graphics) method to save emf in it. And at last I read bytes from temp file.
Don't try to use MemoryStream for Metafile. Unfortunately, it's not working.
This is what I found to be currently the best solution. This is almost like the accepted answer and uses SVG.NET, but is capable of doing it in memory.
The important changes are to release the handle and to reset the position memory stream.
public static Stream ConvertSvgToEmf(string svgImage)
{
using var writeStream = new MemoryStream();
var svg = SvgDocument.FromSvg<SvgDocument>(svgImage);
var stream = new MemoryStream();
var sizedImage = new Bitmap((int)svg.Width.Value, (int)svg.Height.Value);
using (var graphicsFromSizedImage = Graphics.FromImage(Image.FromHbitmap(sizedImage.GetHbitmap())))
using (var metafile = new Metafile(stream, graphicsFromSizedImage.GetHdc(), EmfType.EmfPlusOnly)) // Specify EmfType for lesser file size
using (var graphics = Graphics.FromImage(metafile))
{
svg.Draw(graphics);
graphicsFromSizedImage.ReleaseHdc();
}
stream.Position = 0;
return stream;
}
Be aware that the underlying implementation relies on System.Drawing and therefore the gdi must be accessible. On linux based OS's (or Docker images) libgdiplus must be installed.
As System.Drawing is considered to be deprecated, alternatives like Magick.NET may be better suited for your case.