Java ImageIO 图片处理后变红 解决办法记录

2021-06-19  本文已影响0人  Zal哥哥

原因:根据网上搜罗的一大堆文章以及自己的发现,是因为原始图片(jpeg)带有alpha通道才会变红,在mac上直接显示简介的看到。


image.png

然后发现使用下面这个方式可以解决变红的问题

// 把这行换成下面的方式
BufferedImage image = ImageIO.read(originFile);

// 这里是直接根据url读取图片
public static BufferedImage getBufferedImage(String  imgUrl) throws MalformedURLException {
    URL url = new URL(imgUrl);
    ImageIcon icon = new ImageIcon(url);
    Image image = icon.getImage();
    
    // 如果是从本地加载,就用这种方式,没亲自测试过
    // Image src=Toolkit.getDefaultToolkit().getImage(filePath);

    // This code ensures that all the pixels in the image are loaded
    BufferedImage bimage = null;
    GraphicsEnvironment ge = GraphicsEnvironment
            .getLocalGraphicsEnvironment();
    try {
        int transparency = Transparency.OPAQUE;
        GraphicsDevice gs = ge.getDefaultScreenDevice();
        GraphicsConfiguration gc = gs.getDefaultConfiguration();
        bimage = gc.createCompatibleImage(image.getWidth(null),
                image.getHeight(null), transparency);
    } catch (HeadlessException e) {
        // The system does not have a screen
    }
    if (bimage == null) {
        // Create a buffered image using the default color model
        int type = BufferedImage.TYPE_INT_RGB;
        bimage = new BufferedImage(image.getWidth(null),
                image.getHeight(null), type);
    }
    // Copy image to buffered image
    Graphics g = bimage.createGraphics();
    // Paint the image onto the buffered image
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return bimage;
}

原文链接:https://blog.csdn.net/Wu_Shang001/article/details/108227611

一个完整的例子:

package cn.com.xxx.web.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

@Controller
@RequestMapping("/image")
@Api(tags = "图片处理")
public class ImageController {

    public static BufferedImage getBufferedImage(String  imgUrl) throws MalformedURLException {
        URL url = new URL(imgUrl);
        ImageIcon icon = new ImageIcon(url);
        Image image = icon.getImage();

        // 如果是从本地加载,就用这种方式,没亲自测试过
        // Image src=Toolkit.getDefaultToolkit().getImage(filePath);

        // This code ensures that all the pixels in the image are loaded
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment
                .getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.OPAQUE;
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null),
                    image.getHeight(null), transparency);
        } catch (HeadlessException e) {
            // The system does not have a screen
        }
        if (bimage == null) {
            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            bimage = new BufferedImage(image.getWidth(null),
                    image.getHeight(null), type);
        }
        // Copy image to buffered image
        Graphics g = bimage.createGraphics();
        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;
    }

    /**
     * 获取远程网络图片信息
     * @param imageURL
     * @return
     */
    public BufferedImage getRemoteBufferedImage(String imageURL) {
        URL url = null;
        InputStream is = null;
        BufferedImage bufferedImage = null;
        try {
            url = new URL(imageURL);
            is = url.openStream();
            bufferedImage = ImageIO.read(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.out.println("imageURL: " + imageURL + ",无效!");
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("imageURL: " + imageURL + ",读取失败!");
            return null;
        } finally {
            try {
                if (is!=null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("imageURL: " + imageURL + ",流关闭异常!");
                return null;
            }
        }
        return bufferedImage;
    }

    public BufferedImage mergeImage(String file1Url, String file2Url) throws MalformedURLException {
        BufferedImage b = getBufferedImage(file1Url);
        BufferedImage d = getBufferedImage(file2Url);

        try {
            int w = d.getWidth() / 4; //b.getWidth();
            int h = d.getHeight() / 4; // b.getHeight();
            int x = d.getWidth() / 2 - w / 2;
            int y = d.getHeight() / 2 - h / 2;

            Graphics2D g = d.createGraphics();
            g.drawImage(b, x, y, w, h, null);
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return d;
    }

    /**
     * 根据url进行图片合并
     */
    @ResponseBody
    @RequestMapping(value = "mergeImage", method = RequestMethod.GET)
    @ApiOperation(value = "根据url进行图片合并", httpMethod = "GET")
    public void mergeImage(HttpServletRequest request, HttpServletResponse response) throws MalformedURLException {
        BufferedImage bufferedImage = mergeImage("https://static-oss.cs.kemai.com.cn/vshop/0/c02582c1bba440ae89c216a8e9701daa.png", "https://work-cs.cloud.kemai.cn/img/qr_code.884b6411.png");

        response.setContentType("image/png");
        try (OutputStream out = response.getOutputStream()) {
            //这里直接写入输出流
            ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
        }
    }

}

上一篇下一篇

猜你喜欢

热点阅读