Converting from string to Image in C#

前端 未结 5 2111
生来不讨喜
生来不讨喜 2021-02-20 06:22

I am trying to convert a Unicode string to an image in C#. Each time I run it I get an error on this line

Image image = Image.FromStream(ms, true, true);
         


        
5条回答
  •  南方客
    南方客 (楼主)
    2021-02-20 06:53

    With string you might get loss of data,i will just post example on converting image to byte array and array to image again,and after image to byte array,to string and back,without loss of data.

                MemoryStream ms = new MemoryStream();
                Image.FromFile(@"C:\..\..\..\img.jpg").Save(ms,ImageFormat.Jpeg);
                byte[] bytes = ms.ToArray();
                MemoryStream ms1 = new MemoryStream(bytes);
                Image NewImage = Image.FromStream(ms1);
                NewImage.Save(@"C:\..\..\..\img1.jpg");
    

    try this out and it might help you produce what you need.

    trying to convert to string and back,better use base64.

                MemoryStream ms = new MemoryStream();
                Image.FromFile(@"C:\..\..\..\img.jpg").Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] bytes = ms.ToArray();
                string byteString = Convert.ToBase64String(bytes);
                byte[] NewBytes = Convert.FromBase64String(byteString);
                MemoryStream ms1 = new MemoryStream(NewBytes);
                Image NewImage = Image.FromStream(ms1);
    

    This should give you the outcome you need.

     MemoryStream ms = new MemoryStream();
        Image.FromFile(@"C:\..\..\..\img.jpg").Save(ms,ImageFormat.Jpeg);
        byte[] bytes = ms.ToArray();
        string byteString = Convert.ToBase64String(bytes);
    

    then when you pass this string into your method...

        public Image stringToImage(string inputString)
        {
             byte[] NewBytes = Convert.FromBase64String(inputString);
             MemoryStream ms1 = new MemoryStream(NewBytes);
             Image NewImage = Image.FromStream(ms1);
    
             return NewImage;
         }
    

提交回复
热议问题