Fetching an image

43 views
Skip to first unread message

david.ri...@enquora.com

unread,
Jul 1, 2016, 1:48:09 AM7/1/16
to Cappuccino & Objective-J
I'm fetching an PNG image and unsuccessfully attempting to decode and display it using a CPImageView.
The URL is protected by basic authentication but does not end in .png - is this a problem? (The response data seems about the correct size when logged to the console).
The response is base64 encoded and displays properly in browsers.

I'm using the following code in the CPURLConnection delegate:

- (void)connection:(CPURLConnection)connection didReceiveData:(CPData)data
{
    // Should this not work as well?
    // var image = [[CPImage alloc] initWithData:[CPData dataWithBase64:data]];

    var imageData = [[CPData alloc] initWithRawString:data];
    var image = [[CPImage alloc] initWithData:imageData];
    [image setDelegate:self];
    //...
}

also used in this link,
but seeing the CPImage delegate - (void)imageDidError:(CPImage)image invoked.
How does one determine details for the error that invoked the delegate method?

Once this problem is solved, I need to inspect the image dimensions and adjust neighbouring view positions based on the size.
Is the CPImage delegate method - (void)imageDidLoad:(CPImage)image the correct place to do this, also as suggested in the linked thread?


Todd Freese

unread,
Jul 1, 2016, 10:32:07 AM7/1/16
to Cappuccino & Objective-J
I had to deal with this but with jpgs. Here is the code I use which works really well. It should be easy to adapt for a png.        


// To get an image with basic auth, you can't use the normal CPURLConnection & CPImage way.
// You must manually build an XMLHttpRequest with auth header, override the response mime type,
// and process the responseText to base64. Then make a CPImage from that.
var xhr = new XMLHttpRequest();
xhr.open('GET', SBWC_SERVER_URL + encodeURIComponent(scene_id) + "/" + encodeURIComponent(pictureName), true);
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.setRequestHeader("Authorization", "Basic " + SBWC_BASIC_AUTH);

xhr.onload = function(e) {
var binary = '';
for (var i = 0; i < xhr.responseText.length; i++) {
binary += String.fromCharCode(xhr.responseText.charCodeAt(i) & 0xff);
}

picture = [[CPImage alloc] initWithContentsOfFile:"data:image/jpg;base64," + window.btoa(binary)];
[picture setDelegate:self]; // CPImageView gets it's image set in CPImage imageDidLoad delegate callback.
};

xhr.send();
Reply all
Reply to author
Forward
0 new messages