According to the image encoding example here I should be able to use JpegBitmapEncoder to encode an image for saving as a jpeg file but get this compile error:
error CS1503: Argument 1: cannot convert from 'System.Windows.Controls.Image' to 'System.Uri'
I don't see a way (property or method in Image) to get System.Uri from Image.
What am I missing?
The Image xaml code is
<Image Name="ColorImage"/>
The SaveImage C# is
...
SaveImage(ColorImage, path);
...
private void SaveImage(Image image, string path)
{
var jpegEncoder = new JpegBitmapEncoder();
jpegEncoder.Frames.Add(BitmapFrame.Create(image));
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
jpegEncoder.Save(fs);
}
}
The code below (taken mostly from the kinect-sdk) streams 640 x 480 RBG to a WriteableBitmap at 30 Fps (the kinect ColorImageFormat is RgbResolution640x480Fps30).
using (var colorImageFrame = allFramesReadyEventArgs.OpenColorImageFrame())
{
if (colorImageFrame == null) return;
var haveNewFormat = currentColorImageFormat != colorImageFrame.Format;
if (haveNewFormat)
{
currentColorImageFormat = colorImageFrame.Format;
colorImageData = new byte[colorImageFrame.PixelDataLength];
colorImageWritableBitmap = new WriteableBitmap(
colorImageFrame.Width,
colorImageFrame.Height, 96, 96, PixelFormats.Bgr32, null);
ColorImage.Source = colorImageWritableBitmap;
}
// Make a copy of the color frame for displaying.
colorImageFrame.CopyPixelDataTo(colorImageData);
colorImageWritableBitmap.WritePixels(
new Int32Rect(0, 0, colorImageFrame.Width, colorImageFrame.Height),
colorImageData,
colorImageFrame.Width*Bgr32BytesPerPixel,
0);
}
private void SaveImage(string path)
{
var jpegEncoder = new JpegBitmapEncoder();
jpegEncoder.Frames.Add(BitmapFrame.Create(colorImageWritableBitmap));
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
jpegEncoder.Save(fs);
}
}
The problem occurs, because you pass an Image to BitmapFrame.Create. Imageis more common in Windows Forms. A simple approach would be to create a MemoryStream first and the pass this:
private void SaveImage(Image image, string path)
{
MemoryStream ms = new MemoryStream();
image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
var jpegEncoder = new JpegBitmapEncoder();
jpegEncoder.Frames.Add(BitmapFrame.Create(ms));
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
jpegEncoder.Save(fs);
}
}
Addition (see conversation in comments):
you could try to use the CopyPixels method on the writeableBitmap object and copy the pixels to a byte array which you load to a MemoryStream and the write it to a Jpeg File withe the JpegBitmapEncoder. But it's just a guess.
This could work, too:
private void SaveImage (WriteableBitmap img, string path)
{
FileStream stream = new FileStream(path, FileMode.Create);
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(img));
encoder.Save(stream);
stream.Close();
}
You will just have to extract the WriteableBitmap from your Image control
Try: BitmapFrame.Create(image.Source)
Related
ESRI Symbology library is slow and sometimes take longer time than expected.
I wish to serialize a selected range of ImageSource to a cache, string in the memory or file.
I have searched the web but not much on ImageSource.
An interesting thing I have found is "ImageSourceValueSerializer".
Being a 3 months old baby in WPF, I am not so sure how to go about this.
here's how I got the ImageSource:
MultilayerPointSymbol multiLayerSym = await result.GetSymbolAsync() as MultilayerPointSymbol;
RuntimeImage swatch = await multiLayerSym.CreateSwatchAsync();
ImageSource symbolImage = await swatch.ToImageSourceAsync();
Tested Clemen's, the routine:
MultilayerPointSymbol multiLayerSym = await result.GetSymbolAsync() as MultilayerPointSymbol;
RuntimeImage swatch = await multiLayerSym.CreateSwatchAsync();
ImageSource symbolImage = await swatch.ToImageSourceAsync();
byte[] b = ImageSourceBinary(symbolImage);
ImageSource test = BinaryImageSource(b);
In the class:
private byte[] ImageSourceBinary(ImageSource imageSrc)
{
if (imageSrc is BitmapSource bitmapSource)
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
using (MemoryStream stream = new MemoryStream())
{
encoder.Save(stream);
return stream.ToArray();
}
}
return null;
}
private ImageSource BinaryImageSource(byte[] bytes)
{
using (MemoryStream stream = new MemoryStream(bytes))
{
PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.Default);
BitmapFrame bf = decoder.Frames[0];
if (bf is ImageSource imagesource)
return imagesource;
return null;
}
}
The outcome, no image! :(
Check if the ImageSource is a BitmapSource and encode the BitmapSource by one of the BitmapEncoders. Encode into a MemoryStream or a FileStream.
private byte[] ImageSourceToByteArray(ImageSource imageSrc)
{
if (symbolImage is BitmapSource bitmapSource)
{
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
using (var stream = new MemoryStream())
{
encoder.Save(stream);
return stream.ToArray();
}
}
return null;
}
In order to decode an image from a byte array, do not explictly use a specific BitmapDecoder. Better rely on automatic decoder selection, like shown below. It is also important to set BitmapCacheOption.OnLoad when the stream is closed right after decoding.
private ImageSource ByteArrayToImageSource(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
{
return BitmapFrame.Create(
stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
}
I made a QR-Code Encoder (WPF, c#) by using ZXing.net
I am displaying the QR-Code in an Image-Control
var writer = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new ZXing.Common.EncodingOptions
{
Height = 200,
Width = 200,
Margin = 0
}
};
var image = writer.Write(qrtext.Text);
qrImg.Source = image;
After that I want to save the image. I was using this example Save Image in a Folder.
private void btnSaveImg_Click(object sender, RoutedEventArgs e)
{
string filePath = #"C:\Users\xxx\Desktop\image.png";
SaveToPng(qrImg, filePath);
}
void SaveToBmp(FrameworkElement visual, string fileName)
{
var encoder = new BmpBitmapEncoder();
SaveUsingEncoder(visual, fileName, encoder);
}
void SaveToPng(FrameworkElement visual, string fileName)
{
var encoder = new PngBitmapEncoder();
SaveUsingEncoder(visual, fileName, encoder);
}
// and so on for other encoders (if you want)
void SaveUsingEncoder(FrameworkElement visual, string fileName, BitmapEncoder encoder)
{
RenderTargetBitmap bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(visual);
BitmapFrame frame = BitmapFrame.Create(bitmap);
encoder.Frames.Add(frame);
using (var stream = File.Create(fileName))
{
encoder.Save(stream);
}
}
Unfortunately the image is not being saved. Furthermore, I get no exception. Hope you see my mistake.
Thx a lot
I found another solution, based on this post: How can I save the picture on image control in wpf?
So my solution, that works for me, is:
String filePath = #"C:\Users\xxx\Desktop\test.jpg";
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create((BitmapSource)qrImg.Source));
using (FileStream stream = new FileStream(filePath, FileMode.Create))
encoder.Save(stream);
I need to convert Texture2D to BitmapImage and i found one way to do this, but this solution on windows phone 7 has known issue with memory leak in Texture2D.SaveAsJpeg method call. What i have tried: save texture2d in isolatedstorage by calling Texture2D.SaveAsJpeg, then load from isolatedstorage stream with this texture and create BitmapImage from that stream
public static void SaveTextureToISF(string fileName, Texture2D texture)
{
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
using (
IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Create, file)
)
{
texture.SaveAsPng(fileStream, texture.Width, texture.Height); //Memory leak Here
fileStream.Close();
}
}
}
public static BitmapImage LoadTextureFrom(string fileName)
{
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
using (
IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName,
FileMode.Open,
FileAccess.Read, file))
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(fileStream);
return bmp;
}
}
}
Any other solutions, without leaking?
ImageTools do the trick.
public BitmapImage ConvertTexture2DToBitmapImage(Texture2D texture2D)
{
byte[] textureData = new byte[4 * texture2D.Width * texture2D.Height];
texture2D.GetData(textureData);
ExtendedImage extendedImage = new ExtendedImage();
extendedImage.SetPixels(texture2D.Width, texture2D.Height, textureData);
JpegEncoder encoder = new JpegEncoder();
using (Stream picStream = new MemoryStream())
{
encoder.Encode(extendedImage, picStream);
picStream.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(picStream);
return bitmapImage;
}
}
I have some set of TIFF files (8-bit palette). I need to change the bit depth into 32 bit.
I tried the code below, but getting an error, that the parameter is not correct... Could you help me to fix it? Or maybe some1 is able to suggest some different solution for my problem.
public static class TiffConverter
{
public static void Convert8To32Bit(string fileName)
{
BitmapSource bitmapSource;
using (Stream imageStreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
bitmapSource = decoder.Frames[0];
}
using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate))
{
ImageCodecInfo tiffCodec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(codec => codec.FormatID.Equals(ImageFormat.Tiff.Guid));
if (tiffCodec != null)
{
Image image = BitmapFromSource(bitmapSource);
EncoderParameters parameters = new EncoderParameters();
parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 32);
image.Save(stream, tiffCodec, parameters);
}
}
}
private static Bitmap BitmapFromSource(BitmapSource bitmapSource)
{
Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapSource));
enc.Save(outStream);
bitmap = new Bitmap(outStream);
}
return bitmap;
}
}
Thanks in advance!
[edit]
I noticed that the error appears in this line:
image.Save(stream, tiffCodec, parameters);
ArgumentException occured: Parameter is not valid.
If the error you're getting is on the line:
parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 32);
then the problem is that the compiler cannot know if you're referring System.Text.Encoder or System.Drawing.Imaging.Encoder...
Your code should look like this to to avoid any ambiguity:
parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 32);
Edit:
This is an alternative (and tested :)) way of doing the same thing:
Image inputImg = Image.FromFile("input.tif");
var outputImg = new Bitmap(inputImg.Width, inputImg.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (var gr = Graphics.FromImage(outputImg))
gr.DrawImage(inputImg, new Rectangle(0, 0, inputImg.Width, inputImg.Height));
outputImg.Save("output.tif", ImageFormat.Tiff);
I'm trying to save a bitmap to my isolated storage as a png file. I found a library on Codeplex called ImageTools which people have been recommending but when i try it and attempt to open the file it says that its corrupt. Any know what i am doing wrong?
private static void SaveImageToIsolatedStorageAsPng(BitmapImage bitmap, string fileName)
{
//convert to memory stream
MemoryStream memoryStream = new MemoryStream();
WriteableBitmap writableBitmap = new WriteableBitmap(bitmap);
writableBitmap.SaveJpeg(memoryStream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
//encode memory stream as PNG
ExtendedImage image = new ExtendedImage();
image.SetSource(memoryStream);
PngEncoder encoder = new PngEncoder();
//Save to IsolatedStorage
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var writeStream = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
{
encoder.Encode(image, writeStream);
}
}
You're attempting to convert the JPEG memory stream into PNG. That will make it corrupt - you should save the Bitmap directly to PNG.
I haven't tried this particular task with the imagetools library, but if you see John Papa's blog, it looks like you need to call the ToImage extension method on your WriteableBitmap which is provided as part of ImageTools. Then you can use the encoder to take this image and write out to your open stream.
var img = bitmap.ToImage();
var encoder = new PngEncoder();
using (var stream = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
{
encoder.Encode(img, stream);
stream.Close();
}