I need to stream an image to a .NET backend service using Windows 1252 encoding. So I believe I need to create a NSURLRequest
with its HTTPBodyStream
set to a NSInputStream
which is created with image data. And I need the encoding to be set to Windows 1252 or NSWindowsCP1252StringEncoding
.
I really have two questions:
NSInputStream
to use NSWindowsCP1252StringEncoding
for its passed in data or file.Edit:
This is the example .NET code that mimics a working client.
wr.Method = "POST";
wr.ContentType = "application/octet-stream";
wr.UseDefaultCredentials = true;
string ImagePath = @"C:\Users\smith\Desktop\Cat-and-dog.jpg";
byte[] ibuffer = File.ReadAllBytes(ImagePath);
wr.ContentLength = ibuffer.Length;
Stream pData = wr.GetRequestStream();
pData.Write(ibuffer, 0, ibuffer.Length);
pData.Close();
HttpWebResponse wres = wr.GetResponse() as HttpWebResponse;
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader strRdr = new StreamReader(wres.GetResponseStream(), enc);
string resp = strRdr.ReadToEnd();
You don't tell NSInputStream
what encoding to use, because NSInputStream
doesn't operate on strings. NSInputStream
gives you raw bytes. It's your responsibility to decode those bytes using whatever input format you want.
Also, since you “need to stream an image to a .NET backend service”, I think you want an NSOutputStream
, not an NSInputStream
. But it's the same deal: you give raw bytes to the output stream. You must encode your strings to bytes yourself.
The idea of converting a UIImage
to any character encoding is somewhat nonsensical, because a UIImage
is pixel data, not text. You first have to decode how you want to encode the pixel data. Let's say you want to encode it using PNG:
UIImage *image = ...
NSData *imageData = UIImagePNGRepresentation(image);
NSData *imageBase64Data = [imageData base64EncodedDataWithOptions:0];
At this point, imageBase64Data
contains the image, encoded as PNG, encoded as base 64, encoded as UTF-8. You might think that's the wrong character encoding, but base 64 encoding only uses printable ASCII characters. Since both CP1252 and UTF-8 are supersets of ASCII, the contents of imageBase64Data
is also valid CP1252.
If you'd rather have a string to explicitly encode, you can do this instead:
NSString *imageBase64String = [imageData base64EncodedStringWithOptions::0];
NSData *imageBase64Data = [imageBase64String dataUsingEncoding: NSWindowsCP1252StringEncoding];