Convert Image in Byte array with the same PixelFormat

Abraham Carrillo 31 Reputation points
2023-01-27T21:45:58.9266667+00:00

Hi

I had a System.Drawing.Image object with PixelFormat.Format8bppIndexed,

If I convert it in a Byte Array through Image.Save(Stream, ImageFormat), and create a new image based in this Byte Array, the new image has PixelFormat.Format24bppRgb.

My final purpose is to send the image in Base64String, but preserve the format of the image.

¿How can I do that?

Regards

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,396 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 24,296 Reputation points Microsoft Vendor
    2023-01-30T05:09:14.9833333+00:00

    @Abraham Carrillo , Welcome to Microsoft Q&A, you could convert your image to Bitmap and then you could use Bitmap set the PixelFormat.

    Here is a code example you could refer to.

          private void button1_Click(object sender, EventArgs e)
            {
                Image img = Image.FromFile("C:\\Users\\Administrator\\Desktop\\Icon.bmp");
                Console.WriteLine(img.PixelFormat);
                var brr=ImageToByteArray(img);
                Image newimg=byteArrayToImage(brr,img.PixelFormat);
                Console.WriteLine(newimg.PixelFormat);
            }
    
            public byte[] ImageToByteArray(System.Drawing.Image imageIn)
            {
                using (var ms = new MemoryStream())
                {
                    imageIn.Save(ms, imageIn.RawFormat);
                    return ms.ToArray();
                }
            }
            public Image byteArrayToImage(byte[] byteArrayIn, PixelFormat format)
            {
                MemoryStream ms = new MemoryStream(byteArrayIn);
                Image returnImage = Image.FromStream(ms);
                Bitmap bitmap=(Bitmap)returnImage;
                Bitmap clone = new Bitmap(bitmap.Width, bitmap.Height,format);
                using (Graphics gr = Graphics.FromImage(clone))
                {
                    gr.DrawImage(bitmap, new Rectangle(0, 0, clone.Width, clone.Height));
                }
                return clone;
            }
    
    

    Hope my code could help you.

    Best Regards,

    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments