JAVA - 上传PNG图像时获取黑色背景

时间:2017-12-29 03:21:58

标签: java

当我用用户上传的Google的Thumbnailator保存png文件时,我遇到了问题。它失去了透明度。这是我的编码:

@RequestMapping(method = RequestMethod.POST, path = "/upload")
@ResponseBody
public String upload(@RequestPart("file") MultipartFile picture) {
    String originalFileName = picture.getOriginalFilename();
    String suffix = 
         originalFileName.substring(originalFileName.lastIndexOf("."));
    String pictureName = UUID.randomUUID().toString() + suffix;
    String fileSavePath = gunsProperties.getFileUploadPath();
    Thumbnails.of(picture.getInputStream()).outputFormat("png")
        .scale(1f).outputQuality(0.15f)
        .toFile(new File(fileSavePath + pictureName));

    return pictureName;
}
它带来了黑色背景。还有其他方法可以将它保存为透明的png吗?谢谢!

1 个答案:

答案 0 :(得分:0)

直接将其写入文件而不是使用缩略图的东西? 因为你的比例是1.0,你可以直接把它写到磁盘上:

picture.transferTo(new File(fileSamePath + pictureName));

OR

FileOutputStream fos = new FileOutputStream(new File(fileSamePath + pictureName));
fos.write(picture.getBytes());
fos.close();

或尝试指定图像格式:

Thumbnails.of(picture.getInputStream()).imageType(BufferedImage.TYPE_INT_ARGB).outputFormat("png").scale(1f).outputQuality(0.15f).toFile(new File(fileSavePath + pictureName));

这将使其24位透明而不是8位(如果是)。