roqstr
roqstr

Reputation: 554

convert string to image

I'm trying to convert my string into a 173x173 png-image. Is that somehow possible and if yes: how? need the url afterwards to use it on my backtile.

the string can contain letters,numbers, and "-./"

found something like that, but don't seem to work at all:

 private Uri ToImage()
    {
        string imageString = "";

        byte[] imageBytes = Convert.FromBase64String(imageString);
        System.Text.Encoding.UTF8.GetBytes(imageString.ToCharArray(), 0, imageString.ToCharArray().Length - 1,
        imageBytes, 0);

        System.IO.MemoryStream ms = new System.IO.MemoryStream(imageBytes, 0, imageBytes.Length);

        ms.Write(imageBytes, 0, imageBytes.Length);

        BitmapImage bitmapImage = new BitmapImage();
        bitmapImage.SetSource(ms);
        return bitmapImage.UriSource;
    }

Upvotes: 0

Views: 695

Answers (2)

Edy Cu
Edy Cu

Reputation: 3352

Just remove/comment line code of public abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex);

System.Text.Encoding.UTF8.GetBytes(imageString.ToCharArray(), 0, imageString.ToCharArray().Length - 1,
        imageBytes, 0);

It work on me.

And more thing, convert using line code

Image img;
byte[] fileBytes = Convert.FromBase64String(imageString);
using(MemoryStream ms = new MemoryStream())
{
    ms.Write(fileBytes, 0, fileBytes.Length);
    img = Image.FromStream(ms);
}

don't work. Since in Windows Phone 7 don't provide method Image.FromStream(ms).

Upvotes: 0

rkawano
rkawano

Reputation: 2503

To load image fom a base64 string you can use it:

Image img;
byte[] fileBytes = Convert.FromBase64String(imageString);
using(MemoryStream ms = new MemoryStream())
{
    ms.Write(fileBytes, 0, fileBytes.Length);
    img = Image.FromStream(ms);
}

You can save this image on the server and send a URL of file to client or send the image "on-the-fly":

Response.ContentType = "image/png";
img.Save(Response.OutputStream, ImageFormat.Png);

In this case, the image url are the page url, ex.:

img src="getBacktile.aspx?id=XXX"

Upvotes: 1

Related Questions