Alamofire上传PNG到白色背景的烧瓶

时间:2017-07-04 15:34:14

标签: python swift png alamofire python-imaging-library

我正在尝试实现一个Flask后端端点,其中可以上传两个图像,一个背景和一个前景(前景有一个透明背景),它会将前景粘贴到背景上。我有以下Python代码,我已经使用本地文件测试并运行:

background_name = request.args.get("background")
overlay_name = request.args.get("overlay")
output_name = request.args.get("output")

background_data = request.files["background"].read()
overlay_data = request.files["overlay"].read()

background = Image.open(BytesIO(background_data))
overlay = Image.open(BytesIO(overlay_data))

background = background.convert("RGBA")
overlay = overlay.convert("RGBA")

overlay = resize_image(overlay, background.size)
background.paste(overlay, (0, 0, background.size[0], background.size[1],), overlay)
background.save(output_name, "PNG")

但是,当我尝试通过Alamofire和以下代码上传相同的图片时:

Alamofire.upload(multipartFormData: { formData in
        formData.append(bgData, withName: "background", fileName: "background.jpg", mimeType: "image/jpeg")
        formData.append(fgData, withName: "foreground", fileName: "foreground.png", mimeType: "image/png")
    }, to: "http://localhost:8080/image_overlay?background=background%2Ejpg&overlay=overlay%2Epng&output=result%2Epng", encodingCompletion: { result in
        switch result {
        case .success(let upload, _, _):
            upload.validate().responseJSON(completionHandler: { response in
                switch response.result {
                case .success(let value): print("success: \(value)")
                case .failure((let error)): print("response error \(error)")
                }
            })
        case .failure(let error):
            print("encoding error \(error)")
        }
    })

前景显示为白色背景而不是透明背景,结果图像只是具有白色背景的前景。如何让Alamofire发送透明度?

编辑: 我尝试将其转换为cURL请求,它按预期工作。我使用nc -l localhost 8080查看完整请求,看起来对于前景图片,即使Content-Type设置为“application / octet-stream”,下一行也是“?PNG”。这条线没有出现在Alamofire请求中。如何获得将图像识别为PNG的请求?

1 个答案:

答案 0 :(得分:4)

我无法相信我这样做,但当我获取图像数据时,我正在使用

let fgData = UIImageJPEGRepresentation(UIImage(named: "overlay.png"), 0.75)

这是我从Swift图像中获取数据的唯一方法,尽管显然它应该是我将其更改为:

let fgData = UIImagePNGRepresentation(UIImage(named: "overlay.png"))