Convert Object or array to System.Drawing.Image

Ahmed Wassim BEN SALEM (ENISo) 241 Reputation points
2021-04-22T13:07:25.073+00:00

Hello Guys ,
i want to know if is there any way to convert object or array of bytes/int to System.Drawing.Image !

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
4,824 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
7,037 questions
No comments
{count} votes

Accepted answer
  1. JessieZhang-MSFT 7,516 Reputation points
    2021-04-23T09:56:17.883+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    I think you should use like this:

    byte [] imageArray // is your data  
    MemoryStream mStream = new MemorySteram ();  
    mStream.write(imageArray,0,imageArray.Length);  
    Image img = Image.FromStream(mStream);  
    img.save(filelocation);  
      
    Bitmap bitmapimg = BitmapFactory.BitmapFactory.DecodeStream(mStream);   
    // if you want to use Bitmap  
    

    For how to use bitmap, you can refer to the following code:

      var bitmap = BitmapFactory.BitmapFactory.DecodeStream(stream);  
    var path = Path.Combine(GetExternalFilesDir(Environment.DirectoryDocuments).AbsolutePath, "sameImagePath.jpg");  
    if (!File.Exists(path))  
    {  
        using (var filestream = new FileStream(path, FileMode.Create))  
        {  
            if (bitmap.Compress(Bitmap.CompressFormat.Jpeg, 50, filestream))  
            {  
                filestream.Flush();  
            }  
            else {} // handle failure case...  
        }  
    }  
    bitmap.Recycle();  
    bitmap.Dispose();  
    

    Refer:https://stackoverflow.com/questions/43899497/create-image-file-from-byte-array-in-documents-xamarin-android

    And there are some similar threads about this, you can check:
    https://stackoverflow.com/questions/49721271/byte-array-to-image-using-c-sharp-in-xamarin
    https://stackoverflow.com/questions/9173904/byte-array-to-image-conversion

    Best Regards,

    Jessie Zhang

    ---
    If the response is helpful, please click "Accept Answer" and upvote it.

    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.

    No comments

1 additional answer

Sort by: Most helpful
  1. Michael Taylor 38,271 Reputation points
    2021-04-22T13:39:27.52+00:00

    An image is more than just an array of bytes. Can you convert a byte array to an image? Yes provided the byte array is actually a correctly formatted image. You cannot however take an arbitrary byte array and convert it to an image. Ultimately you need to start with a valid image. At some point it is OK to convert that to a byte array (such as for serializing over the network) and then convert it back to an image on the other side.

    No comments