views:

6786

answers:

3

Im trying to convert from System.Windows.Controls.Image to byte[] and I didnt know which method from Image class could help in this scenary, by the way I really dont know what should I do, cause in my LINQ model the field appears as Bynary type, I have to change this if I want to save it like a byte[] type? thanks!

I found code posted here, but without using WPF:

 Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
    System.IO.MemoryStream stream = new System.IO.MemoryStream();
    newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
    PHJProjectPhoto myPhoto = new PHJProjectPhoto{
    ProjectPhoto = stream.ToArray(), // <<--- This will convert your stream to a byte[] 
    OrderDate = DateTime.Now, 
    ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,
    ProjectId = selectedProjectId
    };


Thanks!

+4  A: 

I don't know how your Image is declared, but suppose we have this XAML declaration:

<Image x:Name="img">
    <Image.Source>
        <BitmapImage UriSource="test.png" />
    </Image.Source>
</Image>

Then you can convert the contents of test.png to a byte-array like this:

var bmp = img.Source as BitmapImage;

int height = bmp.PixelHeight;
int width  = bmp.PixelWidth;
int stride = width * ((bmp.Format.BitsPerPixel + 7) / 8);

byte[] bits = new byte[height * stride];
bmp.CopyPixels(bits, stride, 0);
gix
my xaml is : <Image Margin="6" Name="firmaUno" Stretch="Fill"> </Image> Im setting source in codebehind, so which is better?
Angel Escobedo
surprise is saving :0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000...:/
Angel Escobedo
it's working. Thank you gix
Junior Mayhé
A: 

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;

would be another way, but difference is this have less bytes[x] than first solution

Angel Escobedo
I think it depends on how you initialize the image. If you set a BitmapImage StreamSource seems to be null.
gix
+1  A: 

Real Solution... if want to save jpg images from an System.Windows.Control.Image when your database mapped field on your ORM is Byte[] / byte[] / Bynary

public byte[] getJPGFromImageControl(BitmapImage imageC)
{
       MemoryStream memStream = new MemoryStream();              
        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(imageC));
        encoder.Save(memStream);
        return memStream.GetBuffer();
}

call as :

getJPGFromImageControl(firmaUno.Source as BitmapImage)

Hopes helps :)

Angel Escobedo