PNG 이미지 배경 투명하게 처리

2020. 2. 3. 19:07JAVA

이거 검색하는게 왜케 힘든지..ㅡㅡ;;

그래서 등록...ㅋ


public static Map<String, Object> loadFile(String path) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    HttpURLConnection conn = null;

    byte[] fileBuffer = null;

    Integer width = null;

    Integer height = null;


    try {

    File fnew=new File(path);


    String extension = getFileExtension(fnew);


    BufferedImage originalImage = ImageIO.read(fnew);


    width = originalImage.getWidth();

    height = originalImage.getHeight();


    if( "png".equals(extension) ) {


    BufferedImage resultImage = imageToBufferedImageTransparency(originalImage, originalImage.getWidth(), originalImage.getHeight());


    ImageIO.write(resultImage, extension, baos);


    } else {

    ImageIO.write(originalImage, extension, baos);

    }

     }catch (IOException e) {

    throw new IOException("Can't read input file! - " + path);

} finally {

if( conn != null )

conn.disconnect();

}

}


private static BufferedImage imageToBufferedImageTransparency(Image image, int width, int height) {

BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

Graphics2D g2 = dest.createGraphics();


g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                g2.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);

                g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);

                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);


g2.drawImage(image, 0, 0, null);

g2.dispose();

return dest;

}


'JAVA' 카테고리의 다른 글

[JAVA] LIST형 Remove 하기  (1) 2019.04.16
[JAVA] URLConnection HTTPS 처리  (1) 2019.03.14
[JAVA] 자동리소스 닫기  (2) 2018.08.02
JSON 사용하기  (0) 2013.06.21