I have two functions: one to convert from image to byte and other to convert from byte to bitmapImage.
So, when I open the window with that images, I convert from byte to bitmapImage and it works great, but when I close and open it again it just keeps on memory and if I continue to do that time and time again it just throws an exception Out Of Memory exception
Image to byte->
private byte[] ConvertImageToBinary(Image img)
{
using (MemoryStream ss = new MemoryStream())
{
img.Save(ss, System.Drawing.Imaging.ImageFormat.Jpeg);
var s = ss.ToArray();
var jpegQuality = 50;
Image image;
using (var inputStream = new MemoryStream(s))
{
image = Image.FromStream(inputStream);
var jpegEncoder = System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders()
.First(c => c.FormatID == System.Drawing.Imaging.ImageFormat.Jpeg.Guid);
var encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, jpegQuality);
Byte[] outputBytes;
using (var outputStream = new MemoryStream())
{
image.Save(outputStream, jpegEncoder, encoderParameters);
return outputBytes = outputStream.ToArray();
}
}
}
}
Byte to bitmap ->
public BitmapImage ConvertBinaryToImage(byte[] array)
{
var image = new BitmapImage();
using (var ms = new MemoryStream(array))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad; // here
image.StreamSource = ms;
image.EndInit();
image.Freeze();
}
return image;
}
When I open the WindowDragAndDrop it loads all the images
But when I close it it still uses the same amount of memory
Image is indeed disposable (https://learn.microsoft.com/en-us/dotnet/api/system.drawing.image?view=netframework-4.8), so you also need:
using (var image = Image.FromStream(inputStream)){
}
Around everywhere you use Image objects.
Related
I'm reading data from a blob in MySQL in Base64 String.
I want to convert this to a BitmapImage.
I've tried many ways, but without success.
Here is an example:
public static BitmapImage Base64ToBitmapImage(this string base64String)
{
byte[] binaryData = Convert.FromBase64String(base64String);
BitmapImage img = new BitmapImage();
img.BeginInit();
img.StreamSource = new MemoryStream(binaryData);
img.EndInit();
return img;
}
One example of blob:
iVBORw0KGgoAAAANSUhEUgAAAIwAAACMCAIAAAAhotZpAAAAAXN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9ATmk6R5QfpMqK7+6MBR+UeQHT58GPdIEi5aaItRFDrtI4zQhgnZcv369e94xzsQs2vXrqeeesoQjhYxBgbZvMmP//Qf/9O9994bcRYlsdgrocACxIIjaWKy1NyU/DWVklz6JLBQX5gup3T/5JNP3nXXXXwtyJwfenGAJDKiRHRu3LhRjjLW25ggICYBCkFXf8IqZL72X7/6sY99zCRBTHWZrb8Qcb4idM5I34RKI2rlmfRr5uxb2fJU+mnVTTe+/R033ax9SVc3MS+sq1asbGlqTu89eC3P9O3bv/2ll3dsf6X/8BG37RXLe4tj4y/9+cWhY4NLl/SY4cD+PjcCDAmgWC5w/jLVvGDBKSf1c6KKHBW7W6yLA5HEs3fccYc8FncBLSJD0uvv7+/L/oPXAkK6c6obq1EwufKJOVcDl2aZ87Of/axDyJxGxSrV5YLFgiOJ34F/gwAtUTo/pDJXZECPVKbRqe6W5XwSCobEDxN5nLBR6Fm9ejVq3fIlxltuueWBBx6IGyCZIEZpE0R9wWLBnUmnBI8LIGSIEkHz0EMPffvb3xZn3pBwsC77mRGZuF4KJpTElZJ1gsm5dffdd993332bN2/OJ8RrMBRiCznjLbyLw+w/m+FlCFd61BjhInqUDz/88BNPPPGTn/wEMbIfK3p7e43FBzpJahFtruYf+MAHIv5ctTEqE0ZpTlQFlzG5ysLEgo4kvgMkcWW+9x0t8S+5vQnJbzt27HjkkUd+8IMfuGQjLwZeffXVziHvpzfffLOrebyB4kYaZK+jK156crYWSTrvYELQqc7XwWU8noyFTMbpUHsa/xvEhUOS6IHKw4WFCyTdBdSDKojHk6GrUqsdXCAkVWqzWCRpEX9r1PyZdMpNdoHtvMXbXQ1gMd3VABYjqQawSFINYJGkGsAiSTWARZJqAIsk1QAWSaoBLJJUA1gkqQawSFINYJGkGsAiSTWARZJqAIsk1QAWSaoBLJJUA1gkqQawSFINYJGkBY+6uv8PydCKtZTj+VcAAAAASUVORK5CYII=
In my project, I used this method to convert an array of bytes to BitmapImage:
public static BitmapImage? ConvertToBitmapImage(byte[]? imageData)
{
if (imageData == null || imageData.Length == 0) return null;
var image = new BitmapImage();
using (var mem = new MemoryStream(imageData))
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
}
image.Freeze();
return image;
}
You can use this function by passing an array of bytes to it:
public static BitmapImage? Base64ToBitmapImage(this string base64String)
{
byte[] binaryData = Convert.FromBase64String(base64String);
return ConvertToBitmapImage(binaryData);
}
you can use this functions.
private string ImageToBase64String(string file)
{
Bitmap bitmap = new Bitmap(file);
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
string strBase64 = Convert.ToBase64String(arr);
return strBase64;
}
private Bitmap Base64StringToImage(string base64)
{
byte[] arr = Convert.FromBase64String(base64);
MemoryStream ms = new MemoryStream(arr);
Bitmap bitmap = new Bitmap(ms);
return bitmap;
}
The code above works fine. The cause of the problem its on MySQL return.
The value from a blob column returns returns as a byte on C# MySQL Lybrary.
And I was converting it to a Base64 String and recoverting to a byte.
I excluded this confusion in my code and problem fixed.
The Goal:
I want to convert an ImageBrush to a byte[].
Why?:
Because I want to print out the image, but I can't create any UI elements besides something like a MessageBox. SO I found an online tool that takes in a byte array and produces an image.
How do I do this in C# (WPF)?
What I've tried so far:
I have already converted the ImageBrush to a BitmapSource as so:
BitmapSource src = (BitmapSource)imageBrush.ImageSource;
and have converted the BitmapSource to a Bitmap Image as so:
private BitmapImage BitmapSourceToBitmapImage(BitmapSource bmpSrc)
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
MemoryStream memoryStream = new MemoryStream();
BitmapImage bImg = new BitmapImage();
encoder.Frames.Add(BitmapFrame.Create(bmpSrc));
encoder.Save(memoryStream);
memoryStream.Position = 0;
bImg.BeginInit();
bImg.StreamSource = memoryStream;
bImg.EndInit();
memoryStream.Close();
return bImg;
}
But for the life of me I cannot get this BitmapImage to a byte array! I have tried this:
private byte[] BitmapImagetoByteArray(BitmapImage bitmapImage) {
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
using(MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
The Problem/Error:
But when the encoder tries to save the memory stream, it says a frame has been disposed... see error message below:
Void SaveFrame(System.Windows.Media.SafeMILHandle, System.Windows.Media.SafeMILHandle, System.Windows.Media.Imaging.BitmapFrame)
Cannot access a disposed object.
System.ObjectDisposedException: Cannot access a disposed object.
at System.Windows.Media.Imaging.BitmapEncoder.SaveFrame(SafeMILHandle frameEncodeHandle, SafeMILHandle encoderOptions, BitmapFrame frame)
at System.Windows.Media.Imaging.BitmapEncoder.Save(Stream stream)
Any help? How can I display the ImageBrush without creating UI elements!
The error was not to set BitmapCacheOption.OnLoad, which is necessary when the source stream is to be closed right after EndInit:
bImg.BeginInit();
bImg.CacheOption = BitmapCacheOption.OnLoad;
bImg.StreamSource = memoryStream;
bImg.EndInit();
memoryStream.Close();
However, creating the intermediate BitmapImage wasn't necessary at all. The code should simply look like this:
private byte[] BitmapSourceToByteArray(BitmapSource bmpSrc)
{
var encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 100;
encoder.Frames.Add(BitmapFrame.Create(bmpSrc));
using (var stream = new MemoryStream())
{
encoder.Save(stream);
return stream.ToArray();
}
}
I'm developing a small application which will get RAW image files, convert them to low quality JPEG's then load those JPEG's as thumbnails into a Grid.
My problem: I am having issues with the UI getting blocked while the images are being converted. I am dynamically adding controls to host those images in the grid just after the conversion is taking place for each image. Also I am binding those images to my Image control's Source with my ControlProperties ViewModel in code-behind.
My coding:
Here I am creating a new instance of my ControlProperties view model and inside I am doing the image conversion at the ImageSource.
cp = new ControlProperties()
{
ImageId = controlCount += 1, ImageSource = ThumbnailCreator.CreateThumbnail(imagePath)
};
My question:
Seeing as the images take a while to load, I am in need to get full control of my UI while they are being converted and added into my grid, but I am not getting it right at all. Can someone please help me with some advice or coding snippets to get me going please?
My ThumbnailCreator class
using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
namespace SomeProjName
{
public class ThumbnailCreator
{
private static string imageLocation;
private static int currentImage;
public static BitmapImage CreateThumbnail(string oldImagePath)
{
ConvertHighQualityRAWImage(oldImagePath);
if (imageLocation != string.Empty && imageLocation != null)
return OpenImage(imageLocation);
else return null;
}
//Creates low quality JPG image from RAW image
private static void ConvertHighQualityRAWImage(string oldImagePath)
{
BitmapImage image = new BitmapImage(new Uri(oldImagePath));
var encoder = new JpegBitmapEncoder() { QualityLevel = 17 };
encoder.Frames.Add(BitmapFrame.Create(image));
using (var filestream = new FileStream(GetImageLocation(), FileMode.Create))
encoder.Save(filestream);
image.UriSource = null;
image.StreamSource = null;
image = null;
GC.WaitForPendingFinalizers();
GC.Collect();
}
//Returns low quality JPG thumbnail to calling method
private static BitmapImage OpenImage(string imagePath)
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.DecodePixelWidth = 283;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(imagePath, UriKind.Relative);
image.EndInit();
DeleteImage();
return image;
}
private static string GetImageLocation()
{
imageLocation = Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "thumbnails")).FullName + GetCurrentImage();
return imageLocation;
}
private static string GetCurrentImage()
{
return "\\" + (currentImage += 1).ToString() + ".jpg";
}
private static void DeleteImage()
{
if (File.Exists(imageLocation))
File.Delete(imageLocation);
}
}
}
You don't need to save your thumbnails to file. Use a MemoryStream instead:
public class ThumbnailCreator
{
public static BitmapImage CreateThumbnail(string imagePath)
{
BitmapFrame source;
using (var stream = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
{
source = BitmapFrame.Create(
stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
var encoder = new JpegBitmapEncoder() { QualityLevel = 17 };
encoder.Frames.Add(BitmapFrame.Create(source));
var bitmap = new BitmapImage();
using (var stream = new MemoryStream())
{
encoder.Save(stream);
stream.Position = 0;
bitmap.BeginInit();
bitmap.DecodePixelWidth = 283;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
}
bitmap.Freeze();
return bitmap;
}
The intermediate encoding and decoding pass doesn't even seem to be necessary, so you could simply write this:
public class ThumbnailCreator
{
public static BitmapImage CreateThumbnail(string imagePath)
{
var bitmap = new BitmapImage();
using (var stream = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
{
bitmap.BeginInit();
bitmap.DecodePixelWidth = 283;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
}
bitmap.Freeze();
return bitmap;
}
}
If you want to call the CreateThumbnail method asynchronously, use Task.Run():
cp.ImageSource = await Task.Run(() => ThumbnailCreator.CreateThumbnail(fileName));
Final Solution:
I just want to add this comment to Clemens solution. I also use the Garbage Collector to stop massive memory usage build-up when loading a lot of images. Here is the final method that I use to create the thumbnails.
public static BitmapImage CreateThumbnail(string imagePath)
{
var bitmap = new BitmapImage();
using (var stream = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
{
bitmap.BeginInit();
bitmap.DecodePixelWidth = 283;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
}
bitmap.Freeze();
GC.WaitForPendingFinalizers();
GC.Collect();
return bitmap;
}
Like in the title. How to convert BitmapeImage to byte in metro style app. Ther is no System.drawing lib.
I need it to use in LuminanaceSource() which need source in byte[].
Have some example, but i dont know how to use it.
BitmapImage bmpImage = new BitmapImage(new Uri(file.Path));
var encoderId = Windows.Graphics.Imaging.BitmapEncoder.JpegEncoderId;
Thanks
these two methods should convert Bitmap image to byte[] and viceversa.
public BitmapImage ImageFromBuffer(Byte[] bytes)
{
MemoryStream stream = new MemoryStream(bytes);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
return image;
}
public Byte[] BufferFromImage(BitmapImage imageSource)
{
Stream stream = imageSource.StreamSource;
Byte[] buffer = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((Int32)stream.Length);
}
}
return buffer;
}
I am trying to extract a BitmapImage from a JPG. This is the code I have:
FileStream fIn = new FileStream(sourceFileName, FileMode.Open); // source JPG
Bitmap dImg = new Bitmap(fIn);
MemoryStream ms = new MemoryStream();
dImg.Save(ms, ImageFormat.Jpeg);
image = new BitmapImage();
image.BeginInit();
image.StreamSource = new MemoryStream(ms.ToArray());
image.EndInit();
ms.Close();
image comes back with a 0 × 0 image, which of course means it didn't work. How do I do this?
Try this:
public void Load(string fileName)
{
using(Stream BitmapStream = System.IO.File.Open(fileName,System.IO.FileMode.Open ))
{
Image img = Image.FromStream(BitmapStream);
mBitmap=new Bitmap(img);
//...do whatever
}
}
Or you can just do this (source):
Bitmap myBmp = Bitmap.FromFile("path here");