Java图片处理

获取图片网络图片,重新绘图,zip打包


ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
zos.putNextEntry(new ZipEntry("我是图片1.png"));

注意:

1.这里new ZipEntry() 里的是文件名,也就是说打包时可以在这里直接对文件重命名。

2.这个名字在同一个打包过程里(同一个zip里),不能重名否则报错。

3.读取互联网上图片的方法尽量不要有本地临时文件,浪费资源还要删除,读取的步骤也会增多,所以最开始就没考虑这种方案。(网上都有图了,没必要)

4.绘图过程如果有jpg,jpeg   最好保证两个图片格式一致,输出图片建议png格式。不然会出现不可预料的情况,比如彩色变黑白、黑色、红色的情况。原因是jpeg对透明的支持上有问题。。。

下载并重新绘图

        HttpServletResponse response = beat().getResponse();
        response.setContentType("application/octet-stream");
        ZipOutputStream zos = null;
        try {
            String downloadFilename = URLEncoder.encode("下载zip包的名字", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);
            zos = new ZipOutputStream(response.getOutputStream());
            for (int i = 0; i < size; i++) {
                QrcodeDTO dto = qrcodeDTOList.get(i);
                String qrcodeUrl = dto.getQrcodeUrl();
                String suffix = "png";
                zos.putNextEntry(new ZipEntry("每个压缩文件的名字" + "." + suffix));
                URL url = new URL(qrcodeUrl);
                BufferedImage image = ImageIO.read(url);
                InputStream back = this.getClass().getClassLoader().getResourceAsStream(Constants.BACKGROUND_IMAGE);
                BufferedImage imageback = ImageIO.read(back);
                // 构建叠加层
                BufferedImage buffImg = ImageUtils.watermark(imageback, image, 54, 13, 1.0f);
                // 添加名称到二维码
                buffImg = ImageUtils.addTextToImage(buffImg,"图片展示文字");
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(buffImg, suffix, os);
                InputStream is = new ByteArrayInputStream(os.toByteArray());
                BufferedInputStream in = new BufferedInputStream(is);
                byte[] buffer = new byte[1024];
                int r = 0;
                while ((r = in.read(buffer)) != -1) {
                    zos.write(buffer, 0, r);
                }
                in.close();
                is.close();
            }
            zos.flush();
            zos.close();
        } catch (IOException e) {
            LOGGER.error("close.downloadZip.io.stream.failure", e);
        } finally {
            try {
                if (zos != null) {
                    zos.flush();
                    zos.close();
                }
            } catch (IOException e) {
                LOGGER.error("close.downloadZip.io.stream.failure", e);
            }
        }

图片处理工具,绘图的用处可以是水印,重新拼装图片等等。


import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;


public class ImageUtils {
    private static final Logger logger = LoggerFactory.getLogger(ImageUtils.class);
    private static ImageUtils imageUtils = new ImageUtils();
    private ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        imageUtils.applicationContext = applicationContext;
    }
    public static ImageUtils getInstance(){
        return imageUtils;
    }
    /**
     *
     * @Title: 构造图片
     * @Description: 生成水印并返回java.awt.image.BufferedImage
//     * @param file
     *            源文件(图片)
//     * @param waterFile
     *            水印文件(图片)
     * @param x
     *            距离右下角的X偏移量
     * @param y
     *            距离右下角的Y偏移量
     * @param alpha
     *            透明度, 选择值从0.0~1.0: 完全透明~完全不透明
     * @return BufferedImage
     * @throws IOException
     */
    public static BufferedImage watermark(BufferedImage buffImg, BufferedImage waterImg, int x, int y, float alpha) throws IOException {
        // 创建Graphics2D对象,用在底图对象上绘图
        Graphics2D g2d = buffImg.createGraphics();
        int waterImgWidth = waterImg.getWidth();
        int waterImgHeight = waterImg.getHeight();
        logger.info("buffImgWidth:{},buffImgHeight:{},waterImgWidth:{},waterImgHeight:{}",buffImg.getWidth(),buffImg.getHeight(),waterImgWidth,waterImgHeight);
        // 在图形和图像中实现混合和透明效果
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
        // 绘制
        g2d.drawImage(waterImg, x, y, waterImgWidth, waterImgHeight, null);
        //透明度设置 结束
        g2d.dispose();// 释放图形上下文使用的系统资源
        return buffImg;
    }

    public static BufferedImage addTextToImage(BufferedImage buffImg, String text) {
        if(StringUtils.isNotBlank(text)){
            Graphics graphics = buffImg.getGraphics();
            graphics.setColor(Color.LIGHT_GRAY);
            graphics.setFont(loadFont(14));
            int strWidth = graphics.getFontMetrics().stringWidth(text);
            logger.info("text["+text+"]strWidth["+strWidth+"]");
            graphics.drawString(text, (538 - strWidth) / 2, 525);
            graphics.dispose();
        }

        return buffImg;
    }
    private static Font loadFont(int fountSize){
        String extFontPath;
        try {
            extFontPath = getInstance().applicationContext.getResource(Constants.BACKGROUND_FONT).getFile().getAbsolutePath();
            logger.info("QrCodeUtil loadFont extFontPath["+extFontPath+"]");
            File file = new File(extFontPath+"/SIMHEI.TTF");
            FileInputStream aixing = new FileInputStream(file);
            Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, aixing);
            //字体大小
            dynamicFont = dynamicFont.deriveFont(Font.PLAIN,fountSize);
            aixing.close();
            logger.info("ImageUtils loadFont FontName["+dynamicFont.getFontName()+"]");
            return dynamicFont;
        } catch (Exception e){
            logger.error("ImageUtils loadFont fail", e);
        }
        return null;
    }
}

补充,重绘图片时有文字,会出现服务器不存在我想要的字体。字体自己制定,字体文件放在项目中可以解决。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值