Getting an Image object from a byte array

前端 未结 4 1189
Happy的楠姐
Happy的楠姐 2021-02-07 08:37

I\'ve got a byte array for an image (stored in the database). I want to create an Image object, create several Images of different sizes and store them back in the database (sa

相关标签:
4条回答
  • 2021-02-07 08:53

    Based on your comments to another answer, you can try this for performing a transformation on an image that's stored in a byte[] then returning 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 pass in the byte[] stored in the database, perform whatever transformations you need to, then return a new byte[] that can be stored back in the database.

    0 讨论(0)
  • 2021-02-07 08:53

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

    With saving it back to a 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 讨论(0)
  • 2021-02-07 09:01

    You'd use a MemoryStream to do this:

    byte[] bytes;
    ...
    using (var ms = new System.IO.MemoryStream(bytes)) {
       using(var img = Image.FromStream(ms)) {
          ...
       }
    }
    
    0 讨论(0)
  • 2021-02-07 09:02

    Only answering the first half of the question: Here's a one-liner solution that works fine for me with a byte array that contains an image of a JPEG file.

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

    EDIT: And here's a slightly more advanced solution: https://stackoverflow.com/a/16576471/253938

    0 讨论(0)
提交回复
热议问题