Solution of Java Cutting and Compressing PNG Picture Transparent Background Color Turning Black

  • 2021-12-12 04:30:27
  • OfStack

Directory Java Cut and Compress PNG Picture, Transparent Background Color Change java ImageIO. write Picture Upload Color Change and Background Color Change

Java cropping and compressing PNG picture, transparent background color turns black


import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File; 
import javax.imageio.ImageIO;
 
/**
 *  Picture tool class 
 */
public class ImageUtil {
 
	/**
	 *  Cutting PNG Picture tool class 
	 * 
	 * @param fromFile
	 *             Source file 
	 * @param toFile
	 *             A cropped file 
	 * @param outputWidth
	 *             Cropping width 
	 * @param outputHeight
	 *             Cutting height 
	 * @param proportion
	 *             Whether it is equal scale 
	 */
	public static void resizePng(File fromFile, File toFile, int outputWidth, int outputHeight,
			boolean proportion) {
		try {
			BufferedImage bi2 = ImageIO.read(fromFile);
			int newWidth;
			int newHeight;
			//  Determine whether it is equal scale 
			if (proportion) {
				//  Calculate the width and height of the output picture for equal scale 
				double rate1 = ((double) bi2.getWidth(null)) / (double) outputWidth + 0.1;
				double rate2 = ((double) bi2.getHeight(null)) / (double) outputHeight + 0.1;
				//  Zoom control is performed according to the large zoom ratio 
				double rate = rate1 < rate2 ? rate1 : rate2;
				newWidth = (int) (((double) bi2.getWidth(null)) / rate);
				newHeight = (int) (((double) bi2.getHeight(null)) / rate);
			} else {
				newWidth = outputWidth; //  Output picture width 
				newHeight = outputHeight; //  Height of output picture 
			}
			BufferedImage to = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
			Graphics2D g2d = to.createGraphics();
			to = g2d.getDeviceConfiguration().createCompatibleImage(newWidth, newHeight,
					Transparency.TRANSLUCENT);
			g2d.dispose();
			g2d = to.createGraphics();
			@SuppressWarnings("static-access")
			Image from = bi2.getScaledInstance(newWidth, newHeight, bi2.SCALE_AREA_AVERAGING);
			g2d.drawImage(from, 0, 0, null);
			g2d.dispose();
			ImageIO.write(to, "png", toFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 
	/**
	 *  Test 
	 */
	public static void main(String[] args) throws Exception {
		File fromFile = new File("c:/wxcking/pic/D77E37CB.png");
		File toFile = new File("c:/wxcking/pic/D77E37CB_thumb.png");
		resizePng(fromFile, toFile, 100, 100, false);
	}
}

java ImageIO. write Image Upload Discoloration and Background Blackening


public void getImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String uri = request.getRequestURI();
        String imgPath = uri.replace("/ofc/rest/img", "");
        File image = new File(imgPath);
        BufferedImage bi = ImageIO.read(image);
        BufferedImage newBi = resizeImagePng(bi.getWidth(), bi.getHeight(),bi);
        Graphics2D g2d = newBi.createGraphics();
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));
        ServletOutputStream out = response.getOutputStream();
        g2d.drawImage(newBi,0,0,null);
        ImageIO.write(newBi,"png", out);
        //ImageIO.write(bi, "jpg", out);
        //saveAs(bi,"jpg", out);
    }

public static BufferedImage resizeImagePng(int x, int y, BufferedImage bfi) {
        BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_ARGB);
        bufferedImage.getGraphics().drawImage(
                bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
        return bufferedImage;
    }

public static void saveAs(BufferedImage image, String formatName, ServletOutputStream outFile) throws IOException {
        if (formatName.equalsIgnoreCase("jpg") || formatName.equalsIgnoreCase("jpeg")) {
            BufferedImage tag = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_BGR);
            Graphics g = tag.getGraphics();
//            Graphics2D gg=tag.createGraphics();
//            tag = gg.getDeviceConfiguration().createCompatibleImage(image.getWidth(), image.getHeight(),Transparency.TRANSLUCENT);
//            gg.dispose();
//            gg = tag.createGraphics();
//            gg.drawImage(image, 0, 0,null);
            g.drawImage(image, 0, 0,image.getWidth(), image.getHeight(),image.getGraphics().getColor(), null); //  Draw a reduced figure 
            g.dispose();
            image = tag;
        }
        ImageIO.write(image, formatName, outFile);
    }

Related articles: