BinaryWrite an Image from a binary string

G

Guest

I am trying to BinaryWrite an image from a binary string that I am storing in the web.config file. The image is just a 1x1 pixel gif. I am setting the content type to "image/gif", but the output is just my string. Any suggestions? Code is below

byte[] bytes = Encoding.UTF8.GetBytes(ConfigurationSettings.AppSettings["PixelBinaryData"].ToString())
httpContext.Response.ContentType = "image/gif";
httpContext.Response.BinaryWrite(bytes)
 
M

mikeb

Bammer22 said:
I am trying to BinaryWrite an image from a binary string that I am storing in the web.config file. The image is just a 1x1 pixel gif. I am setting the content type to "image/gif", but the output is just my string. Any suggestions? Code is below:

byte[] bytes = Encoding.UTF8.GetBytes(ConfigurationSettings.AppSettings["PixelBinaryData"].ToString());
httpContext.Response.ContentType = "image/gif";
httpContext.Response.BinaryWrite(bytes);

I suspect that the string in the web.config is a hex string. Encoding
that to UTF8 will not give you what you want.

You probably want something like (I'm probably duplicating something in
the framework that I've overlooked):

public static byte [] hex2bin( string s) {
if (s == null) {
throw new ArgumentNullException("s");
}
if ((s.Length % 2) != 0) {
throw new FormatException("parameter 's' must have an even
number of hex characters");
}

byte [] result = new byte[ (s.Length)/2];

for (int i = 0; i < result.Length; i++) {
result = byte.Parse( s.Substring( i*2, 2),
System.Globalization.NumberStyles.AllowHexSpecifier);
}

return result;
}
 
J

Jon Skeet [C# MVP]

Bammer22 said:
Thanks mike,
seems like I have a problem since my string is prefixed with 0x.

So take the substring from position 2 and then pass it into hex2bin...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top