Save Bitmapimage to File

How do I save a BitmapImage from memory into a file in WPF C#?

You need to use an encoder to save the image. The following will take the image and save it:

BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));

using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
{
encoder.Save(fileStream);
}

I usually will write this into an extension method since it's a pretty common function for image processing/manipulating applications, such as:

public static void Save(this BitmapImage image, string filePath)
{
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));

using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
{
encoder.Save(fileStream);
}
}

This way you can just call it from the instances of the BitmapImage objects.

Save BitmapImage to File

When you create your BitmapImage from a Uri, time is required to download the image.

If you check the following property, the value will likely be TRUE

objImage.IsDownloading

As such, you much attach a listener to the DownloadCompleted event handler and move all processing to that EventHandler.

objImage.DownloadCompleted += objImage_DownloadCompleted;

Where that handler will look something like:

private void objImage_DownloadCompleted(object sender, EventArgs e)
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
Guid photoID = System.Guid.NewGuid();
String photolocation = photoID.ToString() + ".jpg"; //file name

encoder.Frames.Add(BitmapFrame.Create((BitmapImage)sender));

using (var filestream = new FileStream(photolocation, FileMode.Create))
encoder.Save(filestream);
}

You will likely also want to add another EventHandler for DownloadFailed in order to gracefully handle any error cases.

Edit

Added full sample class based on Ben's comment:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

SavePhoto("http://www.google.ca/intl/en_com/images/srpr/logo1w.png");
}

public void SavePhoto(string istrImagePath)
{
BitmapImage objImage = new BitmapImage(new Uri(istrImagePath, UriKind.RelativeOrAbsolute));

objImage.DownloadCompleted += objImage_DownloadCompleted;
}

private void objImage_DownloadCompleted(object sender, EventArgs e)
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
Guid photoID = System.Guid.NewGuid();
String photolocation = photoID.ToString() + ".jpg"; //file name

encoder.Frames.Add(BitmapFrame.Create((BitmapImage)sender));

using (var filestream = new FileStream(photolocation, FileMode.Create))
encoder.Save(filestream);
}
}

Save BitmapImage to local image file in uwp?

Here is a working method from one of my application.

Basically i am converting the Image Control to RenderTargetBitmap and then saving the image using FileSavePicker.

If do not want to use the Image Control but want to save the Source itself, you need to save a SoftwareBitmap while rendering the Image control and then you an use that to save the Image. Example is Here

    private async void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
var _bitmap = new RenderTargetBitmap();
await _bitmap.RenderAsync(myImageSource); //-----> This is my ImageControl.

var savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
savePicker.FileTypeChoices.Add("Image", new List<string>() { ".jpg" });
savePicker.SuggestedFileName = "Card" + DateTime.Now.ToString("yyyyMMddhhmmss");
StorageFile savefile = await savePicker.PickSaveFileAsync();
if (savefile == null)
return;

var pixels = await _bitmap.GetPixelsAsync();
using (IRandomAccessStream stream = await savefile.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await
BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
byte[] bytes = pixels.ToArray();
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)_bitmap.PixelWidth,
(uint)_bitmap.PixelHeight,
200,
200,
bytes);

await encoder.FlushAsync();
}
}

Problems saving bitmapimage to file

I have found the answer. I just need to use the correct url in the request and then it works perfectly.
public void ReceiveImage(string imageURL)
{
HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageURL);
imageRequest.Method = "GET";
HttpWebResponse imageResponse = (HttpWebResponse)imageRequest.GetResponse();
using (Stream inputStream = imageResponse.GetResponseStream())
{
using (Stream outputStream = File.OpenWrite("SonyCamera.jpg"))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
}
}

How can I save an image as Bitmap Image File?

I believe the OP is referring to the last type of image in this adobe link
Bitmap is merely a container for data, the format of the data that you are storing is defined by the PixelFormat setting. As can be seen "Adobe" Bitmap mode is a 2 color format mode and corresponds to PixelFormat.Format1bppIndexed in C# Bitmap.

You have a couple of constructors for Bitmaps which have the PixelFormat as a parameter.

1.

public Bitmap (int width, int height, System.Drawing.Imaging.PixelFormat format);

2.

public Bitmap (int width, int height, int stride, System.Drawing.Imaging.PixelFormat format, IntPtr scan0);

Storing a BitmapImage in LocalFolder - UWP

It would be easier if you used a WriteableBitmap. For example, the first method would then be:

public static async Task<WriteableBitmap> GetProfilePictureAsync(string userId)
{
StorageFolder pictureFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync("ProfilePictures");
StorageFile pictureFile = await pictureFolder.GetFileAsync(userId + ".jpg");

using (IRandomAccessStream stream = await pictureFile .OpenAsync(FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
WriteableBitmap bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);

await bmp.SetSourceAsync(stream);

return bmp;
}
}

Then you could do:

public static async Task SaveBitmapToFileAsync(WriteableBitmap image, userId)
{
StorageFolder pictureFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("ProfilePictures",CreationCollisionOption.OpenIfExists);
var file = await pictureFolder.CreateFileAsync(userId + ".jpg", CreationCollisionOption.ReplaceExisting);

using (var stream = await file.OpenStreamForWriteAsync())
{
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream.AsRandomAccessStream());
var pixelStream = image.PixelBuffer.AsStream();
byte[] pixels = new byte[image.PixelBuffer.Length];

await pixelStream.ReadAsync(pixels, 0, pixels.Length);

encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)image.PixelWidth, (uint)image.PixelHeight, 96, 96, pixels);

await encoder.FlushAsync();
}
}


Related Topics



Leave a reply



Submit