ASP.NET to convert binary data to string

1k views Asked by At

I'm trying to develop API that returns a profile of employees including their pictures, the images are stored in SQL database as image data type

    TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(Bitmap));
    Bitmap bmp = (Bitmap)typeConverter.ConvertFrom(Emp.img);

    //3
    var Fs = new FileStream(HostingEnvironment.MapPath("~/Images") + @"\I" + id.ToString() + ".png", FileMode.Create);
    bmp.Save(Fs, ImageFormat.Png);
    bmp.Dispose();


    //4
    Image img = Image.FromStream(Fs);
    Fs.Close();
    Fs.Dispose();


    //5
    MemoryStream ms = new MemoryStream();
    img.Save(ms, ImageFormat.Png);


    //6
    response.Content = new ByteArrayContent(ms.ToArray());
    ms.Close();
    ms.Dispose();

    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
    response.StatusCode = HttpStatusCode.OK;

    return response;
} 

I want to use this API in Android Studio where I have to convert the image data type to string or any other applicable data time with Volley.

1

There are 1 answers

0
Stefano Liboni On

I'll use a base64 representation of the image:

byte[] imageAsBytes = File.ReadAllBytes(@"your\path\to\image.png");
string imageAsString = Convert.ToBase64String(imageArray);

Then send it back to the Android Studio client and do the following:

byte[] imageAsStringInAndroidStudio = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

Just check if you have to strip the "data:image/jpg;base64" from the data before parsing it into Android Studio.