使用Java合并图片、修改DPI

项目中有时候需要对图片进行DPI、合并、拼接等的处理:

package com.snow.web.a_test;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Test {
    
    private static String path = "F:\\";
    
    public static void main(String[] args) throws Exception {
        System.out.println("=======================================");
//        String path = "F:\\test.jpg";  
//      File files = new File(path);  
//      handleDpi(files, 300, 300); 

//        String path = "F:\\";  
        File file1 = new File(path, "1.jpg");  
        File file2 = new File(path, "2.png");  
//        mosaicImage(file1, file2); 
        mergeImage(file1, file2); 
    }
    /** 
     * 改变图片DPI 
     * 
     * @param file 
     * @param xDensity 
     * @param yDensity 
     * @throws ImageReadException 
     */  
    public static void handleDpi(File file, int xDensity, int yDensity){  
        try {  
            BufferedImage image = ImageIO.read(file);  
            JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(file));  
            JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image);  
            jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);  
            jpegEncoder.setJPEGEncodeParam(jpegEncodeParam);  
            jpegEncodeParam.setQuality(0.75f, false);  
            jpegEncodeParam.setXDensity(xDensity);  
            jpegEncodeParam.setYDensity(yDensity);  
            jpegEncoder.encode(image, jpegEncodeParam);  
            image.flush();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    } 
    /**
     * 图片拼接
     * @param file1 左边
     * @param file2    右边
     * @throws IOException
     */
    public static void mosaicImage(File file1, File file2) throws IOException {        
        BufferedImage image1 = ImageIO.read(file1);  
        BufferedImage image2 = ImageIO.read(file2);  
  
        BufferedImage combined = new BufferedImage(image1.getWidth() * 2, image1.getHeight(), BufferedImage.TYPE_INT_RGB);  
  
        // paint both images, preserving the alpha channels  
        Graphics g = combined.getGraphics();  
        g.drawImage(image1, 0, 0, null);  
        g.drawImage(image2, image1.getWidth(), 0, null);  
          
        // Save as new image  
        ImageIO.write(combined, "JPG", new File(path, "3.jpg"));  
    }  
    /**
     * 图片合并
     * @param file1 左边
     * @param file2    右边
     * @throws IOException
     */
    public static void mergeImage(File file1, File file2) throws IOException {        
        BufferedImage image1 = ImageIO.read(file1);  
        BufferedImage image2 = ImageIO.read(file2);  
  
        BufferedImage combined = new BufferedImage(image1.getWidth(), image1.getHeight(), BufferedImage.TYPE_INT_RGB);  
  
        // paint both images, preserving the alpha channels  
        Graphics g = combined.getGraphics();  
        System.out.println(image2.getData());
        g.drawImage(image1, 0, 0, null);  
        g.drawImage(image2, 0, 0, image1.getWidth(), image1.getHeight(), null);  
          
        // Save as new image  
        ImageIO.write(combined, "JPG", new File(path, "4.jpg"));  
    }  
    
}

 

修改 PNG 图片DPI 值,可以使用 Java 的 ImageIO 类库和 Apache 的 Sanselan 库。 下面是一个示例代码,它可以读取 PNG 图片修改 DPI 值,并将修改后的图片保存到指定的文件路径: ```java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.commons.imaging.ImageFormat; import org.apache.commons.imaging.ImageReadException; import org.apache.commons.imaging.ImageWriteException; import org.apache.commons.imaging.Imaging; import org.apache.commons.imaging.common.IImageMetadata; import org.apache.commons.imaging.common.RationalNumber; import org.apache.commons.imaging.common.RationalNumberUtilities; import org.apache.commons.imaging.formats.png.PngImageMetadata; import org.apache.commons.imaging.formats.png.PngTextMetadata; import org.apache.commons.imaging.formats.png.chunks.PngChunkType; import org.apache.commons.imaging.formats.png.chunks.PngHeaderChunk; import org.apache.commons.imaging.formats.png.chunks.PngTextChunk; public class ModifyPNGDPI { public static void main(String[] args) throws ImageReadException, IOException, ImageWriteException { // 读取 PNG 图片 BufferedImage image = ImageIO.read(new File("input.png")); // 获取 PNG 图片的元数据 IImageMetadata metadata = Imaging.getMetadata(image, null); // 如果是 PNG 图片,就修改 DPI 值 if (metadata instanceof PngImageMetadata) { PngImageMetadata pngMetadata = (PngImageMetadata) metadata; // 获取 DPI 值 RationalNumber xPixelSize = pngMetadata.getPhysicalPixelWidth(); RationalNumber yPixelSize = pngMetadata.getPhysicalPixelHeight(); // 修改 DPI 值为 300 RationalNumber newPixelSize = RationalNumberUtilities.getRationalNumber(300); // 更新元数据 pngMetadata.setPhysicalPixelWidth(newPixelSize); pngMetadata.setPhysicalPixelHeight(newPixelSize); // 更新文本元数据 PngHeaderChunk headerChunk = pngMetadata.getPngHeader(); PngTextChunk[] textChunks = headerChunk.getTextChunks(); for (PngTextChunk textChunk : textChunks) { if (textChunk.getChunkType().equals(PngChunkType.tEXt)) { PngTextMetadata textMetadata = new PngTextMetadata(textChunk.getKeyword(), textChunk.getText()); if (textMetadata.getKeyword().equals("pHYs")) { textMetadata.setValue("x_pixels_per_unit", "300"); textMetadata.setValue("y_pixels_per_unit", "300"); textMetadata.setValue("unit_specifier", "1"); headerChunk.removeChunk(textChunk); headerChunk.addChunk(new PngTextChunk(textMetadata.getKeyword(), textMetadata.getText())); break; } } } } // 保存修改后的 PNG 图片 ImageIO.write(image, "png", new File("output.png")); } } ``` 上面的代码使用了 Apache 的 Sanselan 库来修改 PNG 图片DPI 值。如果你不想使用这个库,也可以使用 Java 自带的 ImageIO 类库来修改 DPI 值。具体的方法是创建一个新的 PNG 图片,将原图片绘制到新图片上,并设置新图片DPI 值。这种方法的代码如下: ```java import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ModifyPNGDPI { public static void main(String[] args) throws IOException { // 读取 PNG 图片 BufferedImage image = ImageIO.read(new File("input.png")); // 创建新的 PNG 图片 BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); // 绘制原图片到新图片上 Graphics2D g = newImage.createGraphics(); g.drawImage(image, 0, 0, null); // 设置新图片DPI 值 int dpi = 300; int dotsPerMeter = (int) Math.round(dpi / 0.0254); newImage.setDPI(dotsPerMeter, dotsPerMeter); // 保存修改后的 PNG 图片 ImageIO.write(newImage, "png", new File("output.png")); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值