简体   繁体   中英

JAVA - Get black background when uploading PNG image

I am having issue when I save a png file with Google's Thumbnailator uploaded by user. It loses its transparency . Here is my coding:

@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;
}

it puts a black background. Any other way to save it as png with transparent? Thanks!

What writing it to the file directly instead of using the thumbnail thing? Since your scale is 1.0 anyway, you could just write it to disk directly:

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

OR

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

OR try specifying the image format:

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

That'll make it 24-bit with transparency instead of 8-bit (if it is).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM