Getting Image Object from Byte Array

I have a byte array for the image (stored in the database). I want to create an Image object, create several images of different sizes and save them back to the database (save them back to an array of bytes).

I am not worried about part of the database or about resizing. But is there an easy way to upload an Image object without saving the file to the file system, and then return it back to the byte array when I change its size? I would like to do all this in my memory if I can.

Something like: Image myImage = new Image(byte[]); or myImage.Load(byte[]); 
+12
image gdi +
Jul 20 2018-10-12T00:
source share
4 answers

To do this, use a MemoryStream:

 byte[] bytes; ... using (var ms = new System.IO.MemoryStream(bytes)) { using(var img = Image.FromStream(ms)) { ... } } 
+18
Jul 20 '10 at 12:53 on
source share

Based on your comments on another answer, you can try this to perform a conversion on an image that is stored in byte[] , and then return the result as another byte[] .

 public byte[] TransformImage(byte[] imageData) { using(var input = new MemoryStream(imageData)) { using(Image img = Image.FromStream(input)) { // perform your transformations using(var output = new MemoryStream()) { img.Save(output, ImageFormat.Bmp); return output.ToArray(); } } } } 

This will allow you to go through the byte[] stored in the database, perform all necessary conversions, and then return a new byte[] , which can be stored in the database.

+2
Jul 20 '10 at
source share

Answering only the first half of the question: Here is a single-line solution that works great for me with a byte array containing a JPEG image file.

 Image x = (Bitmap)((new ImageConverter()).ConvertFrom(jpegByteArray)); 

EDIT: And here is a slightly more advanced solution: stack overflow

+2
Feb 03 '13 at 14:50
source share

I thought I would add this as an answer to make it more visible.

With saving it back to the byte array:

  public Image localImage; public byte[] ImageBytes; public FUU_Image(byte[] bytes) { using (MemoryStream ImageStream = new System.IO.MemoryStream(bytes)) { localImage = Image.FromStream(ImageStream); } localImage = ResizeImage(localImage); using (MemoryStream ImageStreamOut = new MemoryStream()) { localImage.Save(ImageStreamOut, ImageFormat.Jpeg); ImageBytes = ImageStreamOut.ToArray(); } } 
0
Jul 20 '10 at 13:43
source share



All Articles