beratuslu
beratuslu

Reputation: 1119

Working with Image and Bitmap in c#?

I'm developing a project that includes a picture gallery managing by admin panel. I want to show thumbnail images to admin in the admin panel which is active and will be showing to end user.

Ok. I'm storing images into db in two parameters: ImageData(byte[]), ImageMimeType. So I want to store thumbnail versions of pictures at the when first time store images. I have found some example code to resize and manipulate pictures in this adress link text :

private static Image cropImage(Image img, Rectangle cropArea)
{
   Bitmap bmpImage = new Bitmap(img);
   Bitmap bmpCrop = bmpImage.Clone(cropArea,
   bmpImage.PixelFormat);
   return (Image)(bmpCrop);
}

this function taking a image as a parameter. But I have ImageData(byte[]).

So, How do I convert my byte array to Image and Image to byte array?

Upvotes: 2

Views: 3552

Answers (4)

Iain Ward
Iain Ward

Reputation: 9936

public Image ByteArrayToImage(byte[] byteArrayIn)
{
     MemoryStream ms = new MemoryStream(byteArrayIn);
     Image returnImage = Image.FromStream(ms);
     return returnImage;
}

Found here which also has a lot of other examples

Upvotes: 2

osprey
osprey

Reputation: 29

Somthing like this?

Bitmap bmpImage = new Bitmap(img);
MemoryStream stream = new MemoryStream();
try {
    bmpImage.Save(stream, bmpImage.RawFormat);
    byte[] bytes = stream.ToArray();
}
finally {
    stream.Close();
    ((IDisposable)stream).Dispose();
}

Also you may create MemoryStream from byte[] and then load Image from that stream.

Upvotes: 0

Image from byte array

public Image byteArrayToImage(byte[] byteArray)
{
     MemoryStream ms = new MemoryStream(byteArray);
     return Image.FromStream(ms);
}

Image To byte array

public byte[] imageToByteArray(Image image)
{
 MemoryStream ms = new MemoryStream();
 return image.Save(ms,ImageFormat.Jpeg).ToArray();
}

Upvotes: 2

Ian
Ian

Reputation: 34489

Create the image from a stream:

private static Image cropImage(byte[] imgArray, Rectangle cropArea)
{
   MemoryStream ms = new MemoryStream(imgArray);
   Image img = Image.FromStream(ms);
   Bitmap bmpImage = new Bitmap(img);
   Bitmap bmpCrop = bmpImage.Clone(cropArea,
   bmpImage.PixelFormat);
   return (Image)(bmpCrop);
}

Upvotes: 4

Related Questions