将ASCII编码的PNG字节解压缩/解码为NSString

时间:2014-12-18 19:13:27

标签: objective-c nsstring png nsdata compression

我通过websocket接收一些数据。数据是ASCII编码的PNG字节。我需要将PNG字节解压缩为可读的NSString。 PNG字节包含json数据,因此不是图像,PNG刚刚用于压缩。

我现在的位置是我使用以下内容来获取ASCII编码数据,我认为这是正确的。 dataReceivedViaWebsocket是一个NSString。

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:dataReceivedViaWebsocket options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSASCIIStringEncoding];

这为decodeString产生了以下内容,它至少看起来是正确的,因为PNG在标题中。

\U00000089PNG\r\n\x1a\n

现在我只需要将PNG数据解压缩/解码为NSString,但无法弄清楚如何操作。

编辑:在Javascript中找到一个实现。这在Objective C中是否可行?

/**
 * If a message was compressed as a PNG image (a compression hack since
 * gzipping over WebSockets * is not supported yet), this function places the
 * "image" in a canvas element then decodes the * "image" as a Base64 string.
 *
 * @param data - object containing the PNG data.
 * @param callback - function with params:
 *   * data - the uncompressed data
 */
function decompressPng(data, callback) {
  // Uncompresses the data before sending it through (use image/canvas to do so).
  var image = new Image();
  // When the image loads, extracts the raw data (JSON message).
  image.onload = function() {
    // Creates a local canvas to draw on.
    var canvas = new Canvas();
    var context = canvas.getContext('2d');

    // Sets width and height.
    canvas.width = image.width;
    canvas.height = image.height;

    // Puts the data into the image.
    context.drawImage(image, 0, 0);
    // Grabs the raw, uncompressed data.
    var imageData = context.getImageData(0, 0, image.width, image.height).data;

    // Constructs the JSON.
    var jsonData = '';
    for (var i = 0; i < imageData.length; i += 4) {
      // RGB
      jsonData += String.fromCharCode(imageData[i], imageData[i + 1], imageData[i + 2]);
    }
    callback(JSON.parse(jsonData));
  };
  // Sends the image data to load.
  image.src = 'data:image/png;base64,' + data.data;
}

0 个答案:

没有答案