0

我正在尝试按照Cloud Modules Guide调整 Parse Cloud Code 中的图像大小。

基本思路如下:当对User调用afterSave时,检查小头像是否为空,标准头像是否为空。如果为真,则从 Parse 获取标准配置文件图片,读入缓冲区,创建文件,保存文件,然后将文件添加到用户并保存。不幸的是,该文件似乎没有正确保存。

这是云后保存功能:

    Parse.Cloud.afterSave(Parse.User, function(request) {

    ...

        Parse.Cloud.httpRequest({
        url: request.object.get("profilePicture").url(),
        success: function(response) {
            // The file contents are in response.buffer.

            var image = new Image();
            console.log("Buffer: " + response.buffer );
            console.log("Length " + response.buffer.length);
            image.setData(response.buffer);
            var imgData = image.data();


            // Save the image into a new file.
            var base64 = imgData.toString("base64");
            var scaled = new Parse.File("thumbnail.png", { base64: base64 });
            scaled.save().then(function() {
                request.object.set("profilePictureSmall", scaled);
                request.object.save();
            }, function(error) {
                console.log( "The file either could not be read, or could not be saved to Parse.");
            });
        }
    });
    ...
});

User 对象似乎保存得很好,但保存的图像文件是损坏的图像。

奇怪的是,它console.log("Length " + response.buffer.length);会向控制台输出正确的大小。

console.log("Buffer: " + response.buffer );给出输出:�PNG

知道这里发生了什么吗?

4

1 回答 1

4

问题是这setData()是一个异步调用,您需要等待它完成,然后再进行下一步。

http://parse.com/docs/js/symbols/Image.html#setData

这是一个片段:

Parse.Cloud.httpRequest({
    url: request.object.get("profilePicture").url()
}).then(function(response) {
    var image = new Image();
    return image.setData(response.buffer);
}).then(function(image) {
    // make it fit in 100x100
    var width = 100, height = 100;
    if (image.width() > image.height()) {
        // work out scaled height
        height = image.height() * (100/image.width());
    } else {
        // work out scaled width
        width = image.width() * (100/image.height());
    }
    console.log("..scale to " + width + "x" + height);
    return image.scale({
        width: width,
        height: height
    });
}).then(function(scaledImage) {
    // get the image data in a Buffer
    return scaledImage.data();
}).then(function(buffer) {
    // save the image to a new file
    console.log("..saving file");
    var base64 = buffer.toString("base64");
    var name = "Thumbnail.png";
    var thumbnail = new Parse.File(name, { base64: base64 });
    return thumbnail.save();
}).then(function(thumbnail) {
    // attach the image file to the original object
    console.log("..attaching file");
    request.object.set("profilePictureSmall", thumbnail);
    return request.object.save();
}) /* further chaining here for after-save */;

您基本上必须将您的承诺链接在一起以完成上一步。

于 2014-11-21T01:07:35.043 回答