Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
I working for windows phone app, How to convert image to byte array? as i have to save in SqlLite datatabse. I tried below code, but gives error at '
WriteableBitmap 
' - Invalid pointer.

public byte[] ImageToArray()
        {
            BitmapImage image = new BitmapImage();
            image.CreateOptions = BitmapCreateOptions.None;            
            image.UriSource = new Uri(image1.Source.ToString(), UriKind.Relative);
            WriteableBitmap wbmp = new WriteableBitmap(image);
            MemoryStream ms = new MemoryStream();
            wbmp.SaveJpeg(ms, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
            return ms.ToArray();
        }
Posted
Comments
Sergey Alexandrovich Kryukov 7-Feb-14 13:48pm    
In what line?
What are you doing? Rewriting from image1 to image and storing it in memory? Why? Why not simply store image1 to memory?
—SA

I haven't tested it, but this should do the trick:
C#
public Byte[] BufferFromImage(this 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;
}

This is an extention method. You would put this in it's own class and use it like this:
BitmapImage myImage = new BitmapImage();

...

byte[] imageBytes = myImage.ToByteArray();
 
Share this answer
 
Comments
jawad59 8-Feb-14 4:58am    
I tried your code but gives error at 'StreamSource;' in the line 'Stream stream = imageSource.StreamSource;'
Dave Kreskowiak 8-Feb-14 8:44am    
And the error would be? Hint: helpful!
convert to base64
C#
 using (FileStream stream = new FileStream(indexFile.Path, FileMode.Open, FileAccess.Read))
{
    byte[] objByte = new byte[stream.length];
    string base64 =  base64 = Convert.ToBase64String(objByte);
}
 
Share this answer
 
Comments
Dave Kreskowiak 7-Feb-14 15:42pm    
Wrong...wrong...wrong.
Sergey Alexandrovich Kryukov 20-Feb-14 18:32pm    
Amazing gibberish. How could you post it as "answer"?
—SA
File.ReadAllBytes( string path)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900