Saving Bitmap Images in WPF via C# - c#

I display images in my WPF app using BitmapImage.
However, I would like an easy way to save these (as JPG) to a different location (ideally into a Stream or object that can be passed around).
Is it possible using BitmapImage or do I have to use other means? If so what other means are there for either loading an Image and saving as JPG or converting a BitmapImage into this element to then save off?
Thanks

Something like:
public byte[] GetJPGFromImageControl(BitmapImage imageC)
{
MemoryStream memStream = new MemoryStream();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imageC));
encoder.Save(memStream);
return memStream.GetBuffer();
}
(from: WPF Image to byte[])

Related

Creating a Bitmap object with transparency from a URI of a PNG file

I'm having issues trying to use a PNG image with a build action of 'Resource' with the map marker generation of GMap.NET, which expects type Bitmap.
I create a BitmapImage using the pack Uri, and then convert the BitmapImage to a Bitmap by using the code provided by Sascha Henning in their answer here:
Converting BitmapImage to Bitmap and vice versa
The resulting code is as follows:
BitmapImage bmi = new BitmapImage(
new Uri("pack://application:,,,/Images/MapMarker_JobComplete.png"));
System.Drawing.Bitmap markerBitmap = Helpers.BitmapImageToBitmap(bmi);
GMarkerGoogle marker = new GMarkerGoogle(jobLoc, markerBitmap);
Where Helpers.BitmapImageToBitmap() is:
public static Bitmap BitmapImageToBitmap(BitmapImage bitmapSource)
{
using( MemoryStream outstream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapSource));
enc.Save(outstream);
return new System.Drawing.Bitmap(outstream);
}
}
The above works, but the image is rendered with a black background instead of a transparent background. I can only assume that the conversion to a BitmapImage or from a BitmapImage to Bitmap is responsible.
I found a reference to needing to save PNG images to a lower depth, but with currently installed software (Affinity), I couldn't export with a bit depth of 16 as said, only PNG-8 (bit depth of 8; red background, presumaby due to reduced quality) or the standard PNG-24 (bit depth of 32; black background)
PNG-24 PNG-8
Currently to get the desired results (transparency supported), I use the PNG with a build action of 'Content', with the following code:
System.Drawing.Image imgMarker = System.Drawing.Bitmap.FromFile(
System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"Images/MapMarker_JobComplete.png"));
GMarkerGoogle marker = new GMarkerGoogle(jobLoc, (System.Drawing.Bitmap)imgMarker);
The above works fine, so Bitmap must support transparency, but this leaves me with the PNG files as content and I would prefer them embedded into the executable, as well as be able to use the pack Uri in XAML if/when needed.
It's clear that there's some knowledge that I'm missing or haven't been able to glean out, and there's quite a few topics about people wanting to preserve transparency, but with the end result of a BitmapImage and not a Bitmap like I require.
Copying user2819245's old comment here, as it was/is the answer:
I am not sure, but i guess (based on your explanation) that BmpBitmapEncoder does not support (creating) 32bpp BMPs. Why don't you try using PngBitmapEncoder instead?

C# WPF Image loading and saving

I have been trying to load my image in bitmap image class. But whenever I am trying to save an image (using a third party library called Image Processor) the quality drops. So my question is that:
Is there any way i can save image in its full quality?
src.BeginInit();
src.UriSource = new Uri("picture.jpg", UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
You can achieve image saving without any thirdparty libraries. But you should know, that saving JPEG always drops quality a bit - its a nature of that format, not an issue with library. Using the JpegBitmapEncoder you can configure the quality, and with the maximum value you will not see a picture degradation, but anyway it present. So, consider using of PNG format instead.
Here is a short snippet how to load and save a JPEG image:
// Load from file or any other source.
var uri = new Uri(#"D:\InputImage.jpg");
var bitmap = new BitmapImage(uri);
// Save to file.
var encoder = new JpegBitmapEncoder(); // Or any other, e.g. PngBitmapEncoder for PNG.
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.QualityLevel = 100; // Set quality level 1-100.
using (var stream = new FileStream(#"D:\OutputImage.jpg", FileMode.Create))
{
encoder.Save(stream);
}
WebImage works very well and I use often this class in my application. It has a lot of nice built-in features, for example, saving proportins when resizing an image:
WebImage wi = new WebImage(imageName);
wi.Resize(314, 235, true);
wi.Save(imageName, "png");

Issue while saving clipboard data as image

I have copied some data in Clipboard using MS-Word Com API
Range.CopyAsPicture();
and when I am pasting(Ctrl + v) it on window's paint software its getting displayed.
Issue is while converting Clipboard data to image Using c#
I looked into various link on internet and tried following code which is not working
MemoryStream ms = Clipboard.GetData("DeviceIndependentBitmap") as MemoryStream;
above line returning null
clipboardData.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap)
Above line returning false
Can anyone please suggest how can convert the clipboard data to image.
If all you are looking for is getting the bitmap of the image in the clipboard (or the underlying binary data), look into using GetImage.
Here is a code snippet you can try:
BitmapSource bmpSource = Clipboard.GetImage();
MemoryStream ms = new MemoryStream();
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmpSource));
encoder.Save(ms);
ms.Seek(0, SeekOrigin.Begin);
In case that also doesn't seem to work, you can try looking into this workaround, it doesn't seem directly related, but it might be just what you need.
Apparently MS Office puts images on the clipboard as a stream of PNG bytes, which is actually a really sensible innovation. This image data simply uses the identifier "PNG".
So try this instead:
if (retrievedData.GetDataPresent("PNG"))
{
MemoryStream png_stream = retrievedData.GetData("PNG") as MemoryStream;
if (png_stream != null)
return new Bitmap(png_stream);
}

How to read drawing image (.dwg) from byte array

I have one WPF application in which I am uploading autocad drawing files (.dwg), convert it to byte array and save to database. When I read back that file from byte array, I am getting following error :
No imaging component suitable to complete this operation was found.
My code to convert in byte array is below :
FileStream fs = new FileStream(dlg.FileName, FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
I am trying to get image from byte array using below code :
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CreateOptions = BitmapCreateOptions.None;
bi.CacheOption = BitmapCacheOption.Default;
bi.StreamSource = new MemoryStream(data);
RenderOptions.SetBitmapScalingMode(bi, BitmapScalingMode.Linear);
bi.EndInit();
Above code works fine for other image files like jpg, png, bmp, gif. but not working for dwg file. Can anybody guide me what's wrong in my code ?
Thanks
Times ago I was searching for DWG library in C# and found this one:
http://www.woutware.com/cadlib.html, but after never used it.
You can not threat DWG files like ordinar image files, DWG is fairly complicated format for storing 2D and 3D data as well. And years ago also was a subject of frequent change and all licensing mess.
Hope this helps.
You have answered it yourself!
Above code works fine for other image files like jpg, png, bmp, gif.
but not working for dwg file.
For this to work correctly deserialise the byte array back to as "dwg file" itself and use some APIs to convert it to a bitmap and use that as the image source.
Try using a type converter
FileStream fs = new FileStream(dlg.FileName, FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
TypeConverter tc = TypeDescriptor.GetConverter(typeof(BitmapImage));
BitmapImage bitmap1 = (BitmapImage)tc.ConvertFrom(data);
Try using strm.Seek(0, SeekOrigin.Begin); because it may be possible you must have gone past through the stream with read
One option is to use http://www.opendwg.org/
Although not free, it is non-profit.
But it will only parse the dwg file for you into collection of lines, circles, polygons etc.
You still need to piece together and render the image.

how to convert a jpeg in an array into a bitmap

I have a functioning application in c#/.net that currently accepts raw image data in a bayer format from a set of embedded cameras and converts them to jpeg images. To save transmission time, I have modified the embedded devices to encode the images as jpegs prior to transmission. I'm an experienced embedded programmer but a total c#/.net noob. I have managed to modify the application to save the arrays to file with a jpeg name using this snippet: ( the offset of 5 is to skip header data in the transmission frame)
FileStream stream = File.Create(fileName);
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(multiBuff.msgData, 5, multiBuff.dataSize - 5);
writer.Close();
The files open up fine, but now I want to treat the data as a bitmap without having to save & load from file. I tried the following on the data array:
MemoryStream stream = new MemoryStream(data);
BinaryReader reader = new BinaryReader(stream);
byte[] headerData = reader.ReadBytes(5);
Bitmap bmpImage = new Bitmap(stream);
But this throws a parameter not valid exception. As a newbie, I'm a little overwhelmed with all the classes and methods for images and it seems like what I'm doing should be commonplace, but I can't find any examples in the usual places. Any ideas?
I think you are looking for Bitmap.FromStream() :
Bitmap bmpImage = (Bitmap)Bitmap.FromStream(stream);
Actually using new Bitmap(stream) should have worked as well - this means that the data in the stream does not constitute a valid image - are you sure the jpg is valid? Can you save it to disk and open it i.e. in Paint to test?
You use the Image class.
Image image;
using (MemoryStream stream = new MemoryStream(data))
{
image = Image.FromStream(stream);
}
FYI it didn't work because reader.ReadBytes(5) returns the 5 first bytes of stream not the bytes after position 5

Categories