Cannot save Bitmapsource to Bitmapimage - c#

I am trying to save an image from a users Clipboard. I am able to get all the correct data from the clipboard image into the Bitmapsource. I am trying to save to a Bitmapimage so I can upload a file to a website. When converting the Bitmapsource to a Bitmapimage, all of the Bitmapimages data stays null and will throw an exception.
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.V))
{
if (Clipboard.ContainsImage())
{
BitmapSource bitmapSource = Clipboard.GetImage();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
MemoryStream memoryStream = new MemoryStream();
BitmapImage bImg = new BitmapImage();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
encoder.Save(memoryStream);
bImg.BeginInit();
bImg.StreamSource = new MemoryStream(memoryStream.ToArray());
bImg.EndInit();
var client = new WebClient();
var uri = bImg.UriSource;
var path = uri.AbsolutePath;
//client.UploadFile(link, path);
}
}
}
Both
var uri = bImg.UriSource;
var path = uri.AbsolutePath;
Will throw an unhandled exception of type 'System.NullReferenceException' occurred in WpfApplication1.exe
Additional information: Object reference not set to an instance of an object

Creating a BitmapImage from its StreamSource property will not magically set its UriSource property. You do not need that BitmapImage at all.
Write the original BitmapSource to a FileStream instead of a MemoryStream, and upload that file:
string path = ...
using (var fileStream = new FileStream(path, FileMode.Create))
{
encoder.Save(fileStream);
}
client.UploadFile(link, path);
It may even be unnecessary to create an intermediate file. Just upload the buffer of the MemoryStream:
using (var memoryStream = new MemoryStream())
{
encoder.Save(memoryStream);
client.UploadData(link, memoryStream.ToArray());
}

Related

How to keep EXIF of an edited image?

So my program is fixing some image artefacts, it goes like this:
void FixFile(string path)
{
var bmp = new WriteableBitmap(new BitmapImage(new Uri(path)));
bmp.Lock();
// magick
bmp.Unlock();
using (var stream = new FileStream(path.Replace("DSC", "fix_DSC"), FileMode.Create))
{
var encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
encoder.Save(stream);
}
}
The problem is that fixed image contains no EXIF data. How do I transfer EXIF data from the original image?
Load the source bitmap as BitmapFrame, not BitmapImage. Then pass the Metadata property of the source to the new BitmapFrame that is added to the Frames collection of the encoder.
public void FixFile(string path)
{
var source = BitmapFrame.Create(new Uri(path));
var metadata = (BitmapMetadata)source.Metadata;
var bmp = new WriteableBitmap(source);
bmp.Lock();
// magick
bmp.Unlock();
var target = BitmapFrame.Create(bmp, null, metadata, null); // here
var encoder = new JpegBitmapEncoder();
encoder.Frames.Add(target);
using (var stream = File.OpenWrite(path.Replace("DSC", "fix_DSC")))
{
encoder.Save(stream);
}
}

Convert ImageBrush to byte[]

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();
}
}

System.InvalidOperationException occur when load saved Image from IsolatedStorage

I have found a class from the link ImageCaching
but when i load from isolated storage i got an exeption "System.InvalidOperationException"
here is my code
public static object DownloadFromWeb(Uri imageFileUri)
{
WebClient m_webClient = new WebClient(); //Load from internet
BitmapImage bm = new BitmapImage();
m_webClient.OpenReadCompleted += (o, e) =>
{
if (e.Error != null || e.Cancelled) return;
WriteToIsolatedStorage(IsolatedStorageFile.GetUserStoreForApplication(), e.Result, GetFileNameInIsolatedStorage(imageFileUri));
bm.SetSource(e.Result);
e.Result.Close();
};
m_webClient.OpenReadAsync(imageFileUri);
return bm;
}
public static object ExtractFromLocalStorage(Uri imageFileUri)
{
byte[] data;
string isolatedStoragePath = GetFileNameInIsolatedStorage(imageFileUri); //Load from local storage
if (null == _storage)
{
_storage = IsolatedStorageFile.GetUserStoreForApplication();
}
using (IsolatedStorageFileStream sourceFile = _storage.OpenFile(isolatedStoragePath, FileMode.Open, FileAccess.Read))
{
// Read the entire file and then close it
sourceFile.Read(data, 0, data.Length);
sourceFile.Close();
BitmapImage bm = new BitmapImage();
bm.SetSource(sourceFile);///here got the exeption
return bm;
}
}
so that i can't set the image.
I'm using the converter you mentioned and it works but you modified the method.
Your ExtractFromLocalStorage method isn't the same. You close your stream before to use it with the SetSource method.
Here is the original method code:
private static object ExtractFromLocalStorage(Uri imageFileUri)
{
string isolatedStoragePath = GetFileNameInIsolatedStorage(imageFileUri); //Load from local storage
using (var sourceFile = _storage.OpenFile(isolatedStoragePath, FileMode.Open, FileAccess.Read))
{
BitmapImage bm = new BitmapImage();
bm.SetSource(sourceFile);
return bm;
}
}

C# Load JPG file, extract BitmapImage

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");

How to convert varBinary into image or video when retrieved from database in C#

I am using visual studio 2010, (desktop application) and using LINQ to SQL to save image/video or audio files to database in dataType VarBinary (MAX). This I can do... Problem is, I can't get them and display them in xaml because I can't get the converting part correct. Here is what I have so far (though its not working);
private void bt_Click (object sender, RoutedEventArgs e)
{
databaseDataContext context = new databaseDataContext();
var imageValue = from s in context.Images
where s.imageID == 2
select s.imageFile;
value = imageValue.Single().ToString();
//convert to string and taking down to next method to get converted in image
}
public string value { get; set; }
public object ImageSource //taking from http://stackoverflow.com/
{
get
{
BitmapImage image = new BitmapImage();
try
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.UriSource = new Uri(value, UriKind.Absolute);
image.EndInit();
Grid.Children.Add(image);
}
catch { return DependencyProperty.UnsetValue; } return image;
}
}
I not even sure if I am on the correct track? And I am assuming that video or audio is quite similar methods?
Since your image is stored in binary format in the database, you want to "stream" this into an image object by leveraging the MemoryStream object.
Looking at your code, your solution will look something like this:
BitmapImage bmpImage = new BitmapImage();
MemoryStream msImageStream = new MemoryStream();
msImageStream.Write(value, 0, value.Length);
bmpCardImage.BeginInit();
bmpCardImage.StreamSource = new MemoryStream(msImageStream.ToArray());
bmpCardImage.EndInit();
image.Source = bmpCardImage;
It's very easy, if you have a binary data and want to create an Image object, use this code:
public Image BinaryToImage(byte[] binaryData)
{
MemoryStream ms = new MemoryStream(binaryData);
Image img = Image.FromStream(ms);
return img;
}
If you already have the bytes, to verify that what you saved is correct you can save the bytes to a file and open it....
string tempFile = Path.GetTempFileName();
MemoryStream ms = new MemoryStream(bytes); //bytes that was read from the db
//Here I assume that you're reading a png image, you can put any extension you like is a file name
FileStream stream = new FileStream(tempFile + ".png", FileMode.Create);
ms.WriteTo(stream);
ms.Close();
stream.Close();
//And here we open the file with the default program
Process.Start(tempFile + ".png");
And later you can use the answer of Dillie-O and stream....
Dillie-O's code makes for a very nice extension method:
// from http://stackoverflow.com/questions/5623264/how-to-convert-varbinary-into-image-or-video-when-retrieved-from-database-in-c:
public static BitmapImage ToImage(this Binary b)
{
if (b == null)
return null;
var binary = b.ToArray();
var image = new BitmapImage();
var ms = new MemoryStream();
ms.Write(binary, 0, binary.Length);
image.BeginInit();
image.StreamSource = new MemoryStream(ms.ToArray());
image.EndInit();
return image;
}

Categories