Saving Bitmap as PNG on WP7 - c#

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

Related

How to read .img file in C#

I'm developing a Windows Forms application where one of the things i need to do is, extract the image from .img file. I'm being able to read the normal jpg and png files, but not .img file.
I could not find much information on internet regarding this. I did find some code on msdn and i tried to get it to work. Below is the code and exception that is being thrown.
FileInfo file = new FileInfo(FilePath.Text);
FileStream f1 = new FileStream(FilePath.Text, FileMode.Open,
FileAccess.Read, FileShare.Read);
byte[] BytesOfPic = new byte[Convert.ToInt32(file.Length)];
f1.Read(BytesOfPic, 0, Convert.ToInt32(file.Length));
MemoryStream mStream = new MemoryStream();
mStream.Write(BytesOfPic, 0, Convert.ToInt32(BytesOfPic.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
// ImageBox is name of a PictureBox
ImageBox.image = bm; // this line is throwing the error
Exception caught
System.ArgumentException: Parameter is not valid.
at System.Drawing.Bitmap..ctor(Stream stream, Boolean useIcm)
at A02_Stegnography.Form1.ReadImgFile() in C:\Users\tiwar\Desktop\A02-Stegnography\A02-Stegnography\Form1.cs:line 65
I'm sorry if this is a stupid question. I hope i have provided enough information but if i haven't please let me know.
FileInfo file = new FileInfo(FilePath.Text);
FileStream f1 = new FileStream(FilePath.Text, FileMode.Open,
FileAccess.Read, FileShare.Read);
byte[] BytesOfPic = new byte[Convert.ToInt32(file.Length)];
f1.Read(BytesOfPic, 0, Convert.ToInt32(file.Length));
using (MemoryStream mStream = new MemoryStream())
{
mStream.Write(BytesOfPic, 0, BytesOfPic.Length);
mStream.Seek(0, SeekOrigin.Begin);
Bitmap bm = new Bitmap(mStream);
// ImageBox is name of a PictureBox
ImageBox.image = bm;
}
You can try my solution for problem

Convert bitmapimage into byte array

I am trying to convert bitmap Image to Byte array. I have select all the image by using MediaLibrary class and added it into a list of bitmap images. Here is my code
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!store.DirectoryExists("ImagesZipFolder"))
{
store.CreateDirectory("ImagesZipFolder");
for (int i = 0; i < imgname.Count(); i++)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"ImagesZipFolder\" + imgname[i], System.IO.FileMode.CreateNew, store))
{
byte[] bytes = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wBitmap = new WriteableBitmap(ImgCollection[i]);
wBitmap.SaveJpeg(ms, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
bytes = ms.GetBuffer();
stream.Write(bytes, 0, bytes.Length);
}
// byte[] bytes = Encoding.UTF8.GetBytes(imgname[i]);//new byte[ImgCollection[i].PixelWidth * ImgCollection[i].PixelHeight * 4];
// stream.Write(bytes, 0, bytes.Length);
}
}
}
else {
directory = true;
}
}
Basically what I am trying to do is, selecting all images or photo from device and create a zip file of that images. I was successful in creating a zip file of images. When I extract that file there is some images, but the problem is when I double click on image, I can't see that image. I think the problem is in reading the bytes of image. I am not getting what's wrong? Is my code is correct ?
Perhaps you can try the below. I know this code maintains the image, so if you have no luck using this, you may have a different issue.
// Convert the new image to a byte[]
ImageConverter converter = new ImageConverter();
byte[] newBA = (byte[])converter.ConvertTo(newImage, typeof(byte[]));
The ImageConverter is of the System.Drawing namespace.
Update:
http://msdn.microsoft.com/en-GB/library/system.windows.media.imagesourceconverter.convertto.aspx
You should be able to use this in place of the System.Drawing type I suggested.
There is no need to save the WriteableBitmap to a MemoryStream and then copy it to an IsolatedStorageFileStream. Just save the bitmap directly to the IsolatedStorageFileStream.
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"ImagesZipFolder\" + imgname[i], System.IO.FileMode.CreateNew, store))
{
WriteableBitmap wBitmap = new WriteableBitmap(ImgCollection[i]);
wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
}
This will allow you to save on memory as well. If you really want to save memory, you could reuse the WriteableBitmap.

How to read image dimensions at C# wpf - there is no dispose method for BitmapImage

With the way below i am able to read.
But there is no dispose method so i am not able to delete the file later.
So the below method is getting failed.
I could not come up with a proper solution.
Bitmap class is not recognized in C# 4.5 WPF application.
thank you
DirectoryInfo dInfo = new DirectoryInfo(#"C:\pokemon_files\images\");
FileInfo[] subFiles = dInfo.GetFiles();
BitmapImage myImg;
foreach (var vrImage in subFiles)
{
string srFilePath = vrImage.FullName;
System.Uri myUri = new Uri(srFilePath);
myImg = new BitmapImage(myUri);
if (myImg.Width < 50)
{
File.Delete(srFilePath);
continue;
}
}
I assume the error you get is caused by trying to delete the file which is currently in use
by the bitmap (I don't remember the exception name).
There is a solution to that, that is: making a byte stream.
byte[] imageData;
using(var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using(var binaryReader = new BinaryReader(fileStream))
{
imageData = binaryReader.ReadBytes((int)fileStream.Length);
}
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = new MemoryStream(imageData);
bitmap.EndInit();
//Now you can check the width & height, the file stream should be closed so you can
//delete the file.
[EDIT]
If you don't want to read the bytes by BinaryReader, there's always this solution if you want to read all bytes from the file.

Save Image source to database

I have a WPF Image with a source assign from picture dialog;
this.imgProduct.Source = new BitmapImage(new Uri(op.FileName));
How can I retieve the source, convert it to byte array and save it into database?
Thank you
You have to convert BitmapImage into the byte[] then save it to the database.
var imageSource = this.imgProduct.Source as BitmapImage;
var stream = imageSource.StreamSource;
Byte[] buffer = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((Int32)stream.Length);
}
}
// write buffer to the database
P.S. I haven't tested the code but I think it works!
As long as you have access to the image file in op.FileName it would be very easy to get the file content by e.g.
byte[] imageBuffer = File.ReadAllBytes(op.FileName);
If the image is loaded from a file Uri (as in your example) you could also do this:
byte[] imageBuffer = File.ReadAllBytes(image.UriSource.AbsolutePath);
If you only have the BitmapImage without information about the file that it was loaded from (e.g. when it was loaded from a temporary file or a web resource), you would have to encode it by one of WPFs BitmapEncoders:
byte[] imageBuffer;
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (MemoryStream stream = new MemoryStream())
{
encoder.Save(stream);
imageBuffer = stream.GetBuffer();
}

BitmapImage to byte[]

I have a BitmapImage that I'm using in a WPF application, I later want to save it to a database as a byte array (I guess it's the best way), how can I perform this conversion?
Or, alternatively, is there a better way to save a BitmapImage (or any of its base classes, BitmapSource or ImageSource) to a data repository?
To convert to a byte[] you can use a MemoryStream:
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
using(MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
Instead of the JpegBitmapEncoder you can use whatever BitmapEncoder you like as casperOne said.
If you are using MS SQL you could also use a image-Column as MS SQL supports that datatype, but you still would need to convert the BitmapImage somehow.
You will have to use an instance of a class that derives from BitmapEncoder (such as BmpBitmapEncoder) and call the Save method to save the BitmapSource to a Stream.
You would choose the specific encoder depending on the format you want to save the image in.
write it to a MemoryStream, then you can access the bytes from there.
something kinda like this:
public Byte[] ImageToByte(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;
}
You can give a formate of bitmap:
Image bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics.FromImage(bmp).CopyFromScreen(new Point(0, 0), new Point(0, 0), Screen.PrimaryScreen.Bounds.Size);
MemoryStream m = new MemoryStream();
bmp.Save(m, System.Drawing.Imaging.ImageFormat.Png);
byte[] imageBytes = m.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
Just use a MemoryStream.
byte[] data = null;
using(MemoryStream ms = new MemoryStream())
{
bitmapImage.Save(ms);
data = ms.ToArray();
}

Categories

Resources