iPhone/iPad Base64 Image Encoded - Convert to UIImage - iphone

I have a base64 encoded image recieved via a web service.
How do I convert that string to a UIImage?
Obj-c or C# answers are fine.
Ian

First you need to convert the base64-encoded data into an NSData. This previous question seems to be a good resource on how to do that.
Then you just pass that NSData object to [UIImage imageWithData:...].

I havent't tried but here there seems to be a working sample code ;)
Hope it helps

In iPhone Monotouch C# this is how it is done:
byte[] encodedDataAsBytes = System.Convert.FromBase64String (Base64String);
string decoded = System.Text.Encoding.Unicode.GetString (encodedDataAsBytes);
NSData data = NSData.FromString (decoded, NSStringEncoding.ASCIIStringEncoding);
return UIImage.LoadFromData (data);

I was not able to get BahaiResearch's MonoTouch code to work -- an exception was thrown in NSData -- but was successful with the following:
byte[] encodedDataAsBytes = Convert.FromBase64String ( base64String );
NSData data = NSData.FromArray ( encodedDataAsBytes );
return UIImage.LoadFromData ( data );

Related

Decoding base64 string to image in flutter (Invalid character exception)

Basically I'm trying to convert a base64 jpeg image to normal image in flutter using
Image.memory(base64Decode(stringBase64))
the image initially used to be jp/2 format which isn't supported by flutter so i converted the jp/2 base64 string to bitmap in java and then to base64 string jpeg to be able to decode it in flutter using this code :
public static String encodeToBase64(Bitmap image)
{
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
return imageEncoded;
}
how ever when i try to decode this base64 string in flutter i'm getting this error
Invalid character (at character 77)
/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAIQAABtbnRyUkdC
which is pointing to the last C in the given line.
i don't seem understand where does the issue come from since i can convert my base64 string to image online but in flutter it throws that exception every time
thank you very much #Jamesdlin for the solution that was given in the comments
The issue was due to whitespace in the base64 string , solved by using
base64.decode(photoBase64.replaceAll(RegExp(r'\s'), '')),
If your URI contains data after the comma as it is defined by RFC-2397. Dart's Uri class is based on RFC-3986, so you can't use it.
Split the string by a comma and take the last part of it:
String uri = 'data:image/gif;base64,...';
Uint8List _bytes = base64.decode(uri.split(',').last);
REFERENCE: https://stackoverflow.com/a/59015116/12382178

how to convert into NSString?

I am stuck with utf-8 to NSString. I am getting this data from web service :
{
Description = "漢字仮名交じり文";
Images =
(
{
imageName = "0_25_07_2012_10_32_54_1343212374.jpg";
}
);
Time = "11:00 am";
actId = 290;
actTitle = "漢字仮名交じり文";
}
Now how can i convert 名 (名) this kind of code to NSString?
I'm pretty sure something is wrong with your web service. If the web service response is JSON or XML data, then the JSON or XML parser should have decoded the special characters. Since it did not, the web service mistakenly uses a double decoding of characters outside the ASCII range.
The best solution is to fix it at the source, i.e. in the web service.
If you can't, then use the stringByDecodingHTMLEntities method from this NSString category, e.g.:
NSString* textValue = [response objectForKey: #"Description"];
textValue = [textValue stringByDecodingHTMLEntities];
You will have to run each string property through this method.
The codes that you have here are called numeric character references. They have nothing directly to do with UTF8 in general.
See this question for a summary of answers to your problem

Converting Image to Byte Array

I am looking to convert a signature that is captured from the user.
I have the following
NSData *imageData = UIImagePNGRepresentation(drawImage.image);
NSUInteger len = [imageData length];
byteData = (Byte*)malloc(len);
memcpy(byteData, [imageData bytes], len);
Which I saw from a similar question, My problem is I can't use byteData anywhere, it shoots back a Bad_access error. E Am I converting it properly to a byte Array? If I output imageData to console i get
<89504e47 0d0a1a0a 0000000d 49484452 00000140 0000016f 08060000 003b6a12 49000020 00494441 547801ed 9d07b464 4599c71d 494a5219 5832c210 84251d19 51118519 755d0c18 402489a0 b206c015 44443d0a a8e82a8a 804a7005 040cc0c2 022eac89 a30c02a3 4bf02c41 24391266 605601c9 9267ffff 377d39df f474bfd7 affb7657 75d7afce f9dead9b eaabfa7d f7febb6e ddf0a62c 58b0e079 24084000 02251278 7e898da6 cd108000 044c0001 e4388000 048a2580 00161b7a 1a0e0108 20801c03 108040b1 0410c062 434fc321 00010490 63000210 28960002 586ce869 38042080 00720c40 0002c512 40008b0d 3d0d8700 0410408e 010840a0 58020860 b1a1a7e1 10800002 c8310001 08144b00 012c36f4 341c0210 40003906 20008162 092080c5 869e8643 00020820 c7000420 502c0104 b0d8d0d3 70084000 01e41880 00048a25 8000161b 7a1a0e01 0820801c 03108040 b10410c0 62434fc3 21000104 90630002 10289600 02586ce8 69380420 8000720c 400002c5 1240008b 0d3d0d87 00041040 8e010840 a0580208 60b1a1a7 e1108000 02c83100 0108144b 00012c36 f4341c02 10400039 06200081 62092080 c5869e86 43000208 20c70004 20502c01 04b0d8d etc..
To convert data to string use:
[NSString stringWithCString: encoding:];
[NSString stringWithUTF8String:];
If you want to send it via HTTP use the second one. And make sure it is zero-terminated:
byteData = (Byte*)calloc(len+1, sizeof(Byte));
Solved it. Problem was i was encoding it with the format. I need to do a base64 Encoding. The following the site was was where the answer for the base64 encoder is http://www.cocoadev.com/index.pl?BaseSixtyFour

iphone SDK displaying image in uitableview from image data in JSON string

I'm new to this, so here goes..
I'm having a problem with displaying images in uitableview, that are downloaded from a mysql database. Here's what I'm doing:
converting images using UIImagePNGRepresentation.
uploading to MYSQL database via webservice.
So far so good..
The images are downloaded from MYSQL using JSON.
NSDictionary used to create array of image data from JSON String.
[UIImage imageWithData:[imageArray objectAtIndex:indexpath.row]] fails with error: [NSCFString bytes]: unrecongnised selector sent to instance.
I can understand why this is happening, but don't know how to resolve it. The imageWithData is expecting NSData object, but I've converted the string to NSData with no success.
Any help will be greatly appreciated.
Are you converting to and from data properly?
To data:
NSData* theData;
theData = [theNSString dataUsingEncoding:NSASCIIStringEncoding];
To string:
NSString* theNSString;
theNSString = [[NSString alloc] initWithData:theData encoding:NSASCIIStringEncoding];
Thanks for your response.
Yes I was doing the conversion to/from data, as you stated, the only difference being that I was using NSUTF8StringEncoding rather than NSASCIIStringEncoding.
I've tried it with NSASCIIStringEncoding, but the results is the same. It seems that the converted data is different to that stored on the database.
The data from the JSON string (NSData to NSString) is:
<89504e47 0d0a1a0a 0000000d 49484452 00000087 0000005a 08020000 001d25d2 ac000020 00494441 54780174 bd7778dc e775e73b bdf78e19 f40e1004 c002764a ec942cdb b12ccb55 b6e3123b 8e539e44 cecd3ad7 bbc9c6eb f4dc2789 b3297e9c 4d1cc5b1 2dc9b264 4bb22a25 52ec0401 16f45e07 184ceff3 ....
However, the conversion back to NSData gives the following data:
<3c383935 30346534 37203064 30613161 30612030 30303030 30306420 34393438 34343532 20303030 30303038 37203030 30303030 35612030 38303230 30303020 30303164 32356432 20616330 30303032 30203030 34393434 34312035 34373830.....
This may be the same, but [UIImage imageWithData:theData] returns null image.

Compress/Decompress NSString in objective-c (iphone) using GZIP or deflate

I have a web-service running on Windows Azure which returns JSON that I consume in my iPhone app.
Unfortunately, Windows Azure doesn't seem to support the compression of dynamic responses yet (long story) so I decided to get around it by returning an uncompressed JSON package, which contains a compressed (using GZIP) string.
e.g
{"Error":null,"IsCompressed":true,"Success":true,"Value":"vWsAAB+LCAAAAAAAB..etc.."}
... where value is the compressed string of a complex object represented in JSON.
This was really easy to implement on the server, but for the life of me I can't figure out how to decompress a gzipped NSString into an uncompressed NSString, all the examples I can find for zlib etc are dealing with files etc.
Can anyone give me any clues on how to do this? (I'd also be happy for a solution that used deflate as I could change the server-side implementation to use deflate too).
Thanks!!
Steven
Edit 1: Aaah, I see that ASIHTTPRequest is using the following function in it's source code:
//uncompress gzipped data with zlib
+ (NSData *)uncompressZippedData:(NSData*)compressedData;
... and I'm aware that I can convert NSString to NSData, so I'll see if this leads me anywhere!
Edit 2: Unfortunately, the method described in Edit 1 didn't lead me anywhere.
Edit 3: Following the advice below regarding base64 encoding/decoding, I came up with the following code. The encodedGzippedString is as you can guess, a string "Hello, my name is Steven Elliott" which is gzipped and then converted to a base64 string. Unfortunately, the result that prints using NSLog is just blank.
NSString *encodedGzippedString = #"GgAAAB+LCAAAAAAABADtvQdgHEmWJSYvbcp7f0r1StfgdKEIgGATJNiQQBDswYjN5pLsHWlHIymrKoHKZVZlXWYWQMztnbz33nvvvffee++997o7nU4n99//P1xmZAFs9s5K2smeIYCqyB8/fnwfPyK+uE6X2SJPiyZ93eaX+TI9Lcuiatvx/wOwYc0HGgAAAA==";
NSData *decodedGzippedData = [NSData dataFromBase64String:encodedGzippedString];
NSData* unGzippedJsonData = [ASIHTTPRequest uncompressZippedData:decodedGzippedData];
NSString* unGzippedJsonString = [[NSString alloc] initWithData:unGzippedJsonData encoding:NSASCIIStringEncoding];
NSLog(#"Result: %#", unGzippedJsonString);
After all this time, I finally found a solution to this problem!
None of the answers above helped me, as promising as they all looked. In the end, I was able to compress the string on the server with gzip using the chilkat framework for .net ... and then decompress it on the iphone using the chilkat framework for iOS (not yet released, but available if you email the guy directly).
The chilkat framework made this super easy to do so big thumbs up to the developer!
Your "compressed" string is not raw GZIP'd data, it's in some encoding that allows those bytes to be stored in a string-- looks like base-64 or something like it. To get an NSData out of this, you'll need to decode it into the NSData.
If it's really base-64, check out this blog post an accompanying code:
http://cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html
which will do what you want.
Once you have an NSData object, the ASIHTTPRequest method will probably do as you like.
This worked for me:
from a string gzipeed, then base64 encoded
to un-gzipped string (all utf8).
#import "base64.h"
#import "NSData+Compression.h"
...
+(NSString *)gunzipBase64StrToStr:(NSString *)stringValue {
//now we decode from Base64
Byte inputData[[stringValue lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];//prepare a Byte[]
[[stringValue dataUsingEncoding:NSUTF8StringEncoding] getBytes:inputData];//get the pointer of the data
size_t inputDataSize = (size_t)[stringValue length];
size_t outputDataSize = EstimateBas64DecodedDataSize(inputDataSize);//calculate the decoded data size
Byte outputData[outputDataSize];//prepare a Byte[] for the decoded data
Base64DecodeData(inputData, inputDataSize, outputData, &outputDataSize);//decode the data
NSData *theData = [[NSData alloc] initWithBytes:outputData length:outputDataSize];//create a NSData object from the decoded data
//NSLog(#"DATA: %# \n",[theData description]);
//And now we gunzip:
theData=[theData gzipInflate];//make bigger==gunzip
return [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
}
#end
I needed to compress data on the iPhone using Objective-c and decompress on PHP. Here is what I used in XCode 11.5 and iOS 12.4:
iOS Objective-c Compression Decompression Test
Include libcompression.tbd in the Build Phases -> Link Binary With Library. Then include the header.
#include "compression.h"
NSLog(#"START META DATA COMPRESSION");
NSString *testString = #"THIS IS A COMPRESSION TESTTHIS IS A COMPRESSION TESTTHIS IS A COMPRESSION TESTTHIS IS A COMPRESSION TESTTHIS IS A COMPRESSION TESTTHIS IS A COMPRESSION TEST";
NSData *theData = [testString dataUsingEncoding:NSUTF8StringEncoding];
size_t src_size = theData.length;
uint8_t *src_buffer = (uint8_t*)[theData bytes];
size_t dst_size = src_size+4096;
uint8_t *dst_buffer = (uint8_t*)malloc(dst_size);
dst_size = compression_encode_buffer(dst_buffer, dst_size, src_buffer, src_size, NULL, COMPRESSION_ZLIB);
NSLog(#"originalsize:%zu compressed:%zu", src_size, dst_size);
NSData *dataData = [NSData dataWithBytes:dst_buffer length:sizeof(dst_buffer)];
NSString *compressedDataBase64String = [dataData base64EncodedStringWithOptions:0];
NSLog(#"Compressed Data %#", compressedDataBase64String);
NSLog(#"START META DATA DECOMPRESSION");
src_size = compression_decode_buffer(src_buffer, src_size, dst_buffer, dst_size, NULL, COMPRESSION_ZLIB);
NSData *decompressed = [[NSData alloc] initWithBytes:src_buffer length:src_size];
NSString *decTestString;
decTestString = [[NSString alloc] initWithData:decompressed encoding:NSASCIIStringEncoding];
NSLog(#"DECOMPRESSED DATA %#", decTestString);
free(dst_buffer);
On the PHP side I used the following function to decompress the data:
function decompressString($compressed_string) {
//NEED RAW GZINFLATE FOR COMPATIBILITY WITH IOS COMPRESSION_ZLIB WITH IETF RFC 1951
$full_string = gzinflate($compressed_string);
return $full_string;
}