tif 图片转 png demo

package com.common.util;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.io.*;
import java.util.LinkedList;
import java.util.List;

import javax.imageio.ImageIO;

import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.TIFFDecodeParam;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import static org.attoparser.MarkupParser.DEFAULT_BUFFER_SIZE;

public class ConvertTIF {
	private static final Logger LOGGER = LoggerFactory.getLogger(ConvertTIF.class);

	public  static BufferedImage convertARGBToRGB(BufferedImage image) {

		//DataBufferInt db = (DataBufferInt)image.getRaster().getDataBuffer();

		int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
		BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
		int[] pixelsOut = ((DataBufferInt) result.getRaster().getDataBuffer()).getData();
		System.arraycopy(pixels, 0, pixelsOut, 0, pixels.length);
		return result;
		}


	public static String convertImage(String imageFile, double zoom) throws Exception {
		try {
			// long t1 = System.currentTimeMillis();
			int iIndex = imageFile.lastIndexOf(".");
			String jpgFile = imageFile.substring(0, iIndex) + ".png";
			String rgbImageFile;
			boolean isCMYK=false;
			isCMYK=isCMYK(imageFile);
			if(isCMYK){
				  rgbImageFile=cmyk2rgb(imageFile);
			}else{

				  rgbImageFile=imageFile;
			}

if (new File(imageFile).exists()) {
				Thumbnails.of(new File(imageFile)).size(700, 1200).outputFormat("png").toFile(jpgFile);

//				FileOutputStream out = new FileOutputStream(jpgFile);
/*
				TIFFDecodeParam decodeParm= new TIFFDecodeParam();
//				BufferedImage image;
//				decodeParm.setJPEGDecompressYCbCrToRGB(false);
				ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", new File(rgbImageFile), decodeParm);

//				 jpgEncodeParam param = new jpgEncodeParam();
				// param.setQuality(0.30F);//设置图片质量
				//  jpgEncodeParam param = new jpgEncodeParam.RGB();
				// param.set
//				JpgEncoderParam param = new jpgEncoderParam();
				ImageEncoder encoder = ImageCodec.createImageEncoder("png", out, null);

				//System.out.println("decoder.getNumPages()="+decoder.getNumPages());
				RenderedImage image = decoder.decodeAsRenderedImage();


				encoder.encode(image);
				decoder = null;
				out.close();
*/

				if(isCMYK){
					//删除中间文件
					File file = new File(rgbImageFile);

					if (file.exists()) {

						file.delete();
					}
				}
				return jpgFile;
			}
			// saveImageAsjpg(jpgFile, jpgFile, zoom);
			// long t2 = System.currentTimeMillis();
			// System.out.println("coast time:" + (t2 - t1));
			/*
			File file = new File(imageFile);
			if (file.exists()) {
				file.delete();
			}*/

			return "";

		} catch (Exception ex) {
			LOGGER.error("图片转换报错了");
			LOGGER.error(ex.toString());
			return "";
		}
	}
	@SuppressWarnings("unused")
	private static void saveImageAsjpg(String fromFileStr, String saveToFileStr, double zoom) throws Exception {
		BufferedImage srcImage;
		String imgType = "jpg";
		if (fromFileStr.toLowerCase().endsWith(".jpg")) {
			imgType = "jpg";
		}
		File saveFile = new File(saveToFileStr);
		File fromFile = new File(fromFileStr);
		srcImage = ImageIO.read(fromFile);
		srcImage = resize(srcImage, zoom);
		ImageIO.write(srcImage, imgType, saveFile);
	}

	private static BufferedImage resize(BufferedImage source, double zoom) {
		int type = source.getType();
		BufferedImage target = null;

		double sx = zoom;
		double sy = zoom;

		if (type == BufferedImage.TYPE_CUSTOM) { // handmade
			ColorModel cm = source.getColorModel();
			WritableRaster raster = cm.createCompatibleWritableRaster(source.getWidth() / 2, source.getHeight() / 2);
			boolean alphaPremultiplied = cm.isAlphaPremultiplied();
			target = new BufferedImage(cm, raster, alphaPremultiplied, null);
		} else
	target = new BufferedImage(source.getWidth() / 2, source.getHeight() / 2, type);
		Graphics2D g = target.createGraphics();
		g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
		g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
		g.dispose();
		return target;

	}
	  public static void folderMethod(String path,String ext,Integer date)  {

	        int fileNum = 0,   fileNumfailed = 0 ,totaltif=0;
	        File file = new File(path);
	         List<File> list = new LinkedList<>();

	        if (file.exists()) {
	            if (null == file.listFiles()) {
	                return;
	            }if("".equals(ext)||ext==null){
	            	getFiles(file,list,"tif");
		            getFiles(file,list,"cgm");
	            }else{
	            	getFiles(file,list,ext);
	            }

	                for (File f : list) {

	                    if( f.isFile()){
	                        String fileName = f.getName();
	                        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
	                        if("tif".equals(suffix)){
	                        	double zoom = 1;
	                        	String pngfile = f.getAbsolutePath().replaceAll("."+suffix, ".png");

	                        	File filepng = new File(pngfile);
	                        	//System.out.println("文件:"  +pngfile);
	                        	//folderNum++;
	                        	if(!filepng.exists()){
	                        		totaltif++;
	                        		 try {
	                        			 String fInt = String.valueOf(f.lastModified());
	                        			fInt = fInt.substring(0,10);
	                        			 if(Integer.parseInt(fInt)<date){
	                        				 pngfile=ConvertTIF.convertImage(f.getAbsolutePath(), zoom);
											 fileNum++; 
											 System.out.println("Convert tif file " + f.getAbsolutePath()+" to "+pngfile +" successed");
	                        			 }

									} catch (Exception e) {
										// TODO Auto-generated catch block
										fileNumfailed ++;
										 System.out.println("Convert tif file " + f.getAbsolutePath()+" to "+pngfile +" failed.");
										e.printStackTrace();
									}
	                        	}
	                        	}
	                        if("cgm".equals(suffix)){

	                        	String pngfile = f.getAbsolutePath().replaceAll("."+suffix, ".png");

	                        	File filepng = new File(pngfile);
	                        	//System.out.println("文件:"  +pngfile);
	                        	//folderNum++;
	                        	if(!filepng.exists()){
	                        		totaltif++;
	                        		 try {

										pngfile=ConvertCGM.convertImage(f.getAbsolutePath(), 96*4);
										 fileNum++;
										 System.out.println("Convert cgm file " + f.getAbsolutePath()+" to "+pngfile +" successed");

									} catch (Exception e) {
										// TODO Auto-generated catch block
										fileNumfailed ++;
										 System.out.println("Convert cgm file " + f.getAbsolutePath()+" to "+pngfile +" failed.");
										e.printStackTrace();
									}
	                        	}
	                        }
	                    }
	                }
	              } else {
	            System.out.println("文件不存在!");
	        }
	        System.out.println("需要转换的图片总数量:" +  totaltif + ",成功转换文件数量:" + fileNum +",转换失败数量:"+fileNumfailed);
	    }

	    public static List<File> getFiles(File file ,List<File> list ,String ext){

	        File[] a=file.listFiles();
	        if(a!=null){
	        for(File file1:a){

	            if(file1.isDirectory()){
	            	//System.out.println(file1.getAbsolutePath());
	                getFiles(new File(file1.getAbsolutePath()),list,ext);

	            }else if(file1.isFile()){
	            	 String fileName = file1.getName();
                     String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                     if(ext==null || ext.equals(suffix)){
                    //	 System.out.println("***"+fileName);
                    	 list.add(file1);
                     }


	            }
	        }
	        }
	        return list;

	    }
	    public static boolean isCMYK(String filename)
	    {
	        boolean result = false;
	        BufferedImage img = null;
	        File file = new File(filename);
	        LOGGER.error("文件名为:--------------------"+file.getName());
	        try
	        {
	            img = ImageIO.read(new File(filename));
	        }
	        catch (IOException e)
	        {
	            System.out.println(e.getMessage() + ": " + filename);
	        }
	        if (img != null)
	        {
	        	LOGGER.error("img不为null:--------------------");
	            int colorSpaceType = img.getColorModel().getColorSpace().getType();
	            result = colorSpaceType == ColorSpace.TYPE_CMYK;
	        }else{
	        	LOGGER.error("img为null:--------------------");
	        }

	        return result;
	    }
private static InputStream InputStream() {
		// TODO Auto-generated method stub
		return null;
	}



	public static String cmyk2rgb(String filename) throws IOException
	    {
	        // Change this format into any ImageIO supported format.
	        //String format = "tif";
	        String format = filename.substring(filename.lastIndexOf(".") + 1);
	        File imageFile = new File(filename);
	        String rgbFilename = filename;
	        BufferedImage image = ImageIO.read(imageFile);
	        if (image != null)
	        {
	            int colorSpaceType = image.getColorModel().getColorSpace().getType();
	            if (colorSpaceType == ColorSpace.TYPE_CMYK)
	            {
	                BufferedImage rgbImage =
	                    new BufferedImage(
	                        image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
	                ColorConvertOp op = new ColorConvertOp(null);
	                op.filter(image, rgbImage);
rgbFilename =  imageFile.getName() ;
	                rgbFilename = new File(imageFile.getParent(), format + "_" + rgbFilename).getPath();
	                ImageIO.write(rgbImage, format, new File(rgbFilename));
	            }
	        }
	        return rgbFilename;
	    }

	public static void main(String[] args) throws Exception {
		//System.out.println(args[1]);
		//System.out.println(args[2]);
		//folderMethod(args[1],args[2],1617897507);
//		folderMethod( "Z:/cell/graphics/","tif",1583683107);
		convertImage("Z:\\manualPublish\\cell\\graphics\\541\\5417131.tif",1);
		//System.out.println(ConvertTIF.convertImage("D:/yuanzf/tif/png/123134.tif", 1));
	}

maven 配置

        <dependency>
            <groupId>org.owasp.esapi</groupId>
            <artifactId>esapi</artifactId>
            <version>2.1.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.3</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/itextpdf-5.5.3.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/itext-asian-5.2.0.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>com.sun.media.jai</groupId>
            <artifactId>com.sun.media.jai</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/com.sun.media.jai.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>javax.media.jai</groupId>
            <artifactId>javax.media.jai</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/javax.media.jai.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>jcgm</groupId>
            <artifactId>net.sf.jcgm</artifactId>
            <version>0.2.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/net.sf.jcgm.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>org.apache.batik</groupId>
            <artifactId>org.apache.batik</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/org.apache.batik.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-all</groupId>
            <artifactId>batik-all</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-all-1.9.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-anim</groupId>
            <artifactId>batik-anim</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-anim.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-awt-util</groupId>
            <artifactId>batik-awt-util</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-awt-util.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-bridge</groupId>
            <artifactId>batik-bridge</artifactId>
            <version>1.1.0</version>
     		<scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-bridge.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-codec</groupId>
            <artifactId>batik-codec</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-codec.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-css</groupId>
            <artifactId>batik-css</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-css.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-dom</groupId>
            <artifactId>batik-dom</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-dom.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-ext</groupId>
            <artifactId>batik-ext</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-ext.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-extension</groupId>
            <artifactId>batik-extension</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-extension.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-gui-util</groupId>
            <artifactId>batik-gui-util</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-gui-util.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-gvt</groupId>
            <artifactId>batik-gvt</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-gvt.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-parser</groupId>
            <artifactId>batik-parser</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-parser.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-script</groupId>
            <artifactId>batik-script</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-script.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-svg-dom</groupId>
            <artifactId>batik-svg-dom</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-svg-dom.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-svggen</groupId>
            <artifactId>batik-svggen</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-svggen.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-swing</groupId>
            <artifactId>batik-swing</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-swing.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-transcoder</groupId>
            <artifactId>batik-transcoder</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-transcoder.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-util</groupId>
            <artifactId>batik-util</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-util.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>batik-xml</groupId>
            <artifactId>batik-xml</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/batik-xml.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>common-image</groupId>
            <artifactId>common-image</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/common-image-3.4.2.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>common-io</groupId>
            <artifactId>common-io</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/common-io-3.4.2.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>common-lang</groupId>
            <artifactId>common-lang</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/common-lang-3.4.2.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>fop-transcoder-allinone</groupId>
            <artifactId>fop-transcoder-allinone</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/fop-transcoder-allinone-2.3.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>imageio-batik</groupId>
            <artifactId>imageio-batik</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/imageio-batik-3.4.2.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>imageio-core</groupId>
            <artifactId>imageio-core</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/imageio-core-3.4.2.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>imageio-metadata</groupId>
            <artifactId>imageio-metadata</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/imageio-metadata-3.4.2.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>com.twelvemonkeys.imageio</groupId>
            <artifactId>imageio-tiff</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>jai_core</groupId>
            <artifactId>jai_core</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/jai_core.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>jai-codec</groupId>
            <artifactId>jai-codec</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/jai-codec-1.1.3.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>jcgm-core</groupId>
            <artifactId>jcgm-core</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/jcgm-core-0.2.0.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>jcgm-image</groupId>
            <artifactId>jcgm-image</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/jcgm-image-0.1.1.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>js</groupId>
            <artifactId>js</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/js.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>mlibwrapper_jai</groupId>
            <artifactId>mlibwrapper_jai</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/mlibwrapper_jai.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>sanselan</groupId>
            <artifactId>sanselan</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/sanselan-0.97-incubator.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>serializer</groupId>
            <artifactId>serializer</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/serializer-2.7.2.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>xalan</groupId>
            <artifactId>xalan</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/xalan-2.7.2.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>xercesImpl</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/xercesImpl-2.9.1.jar</systemPath>
        </dependency>
            <dependency>
            <groupId>xml-apis-1.3.04.jar</groupId>
            <artifactId>xml-apis-1.3.04.jar</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/xml-apis-1.3.04.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>xml-apis-ext</groupId>
            <artifactId>xml-apis-ext</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/xml-apis-ext-1.3.04.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>xmlgraphics-commons</groupId>
            <artifactId>xmlgraphics-commons</artifactId>
            <version>1.1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/xmlgraphics-commons-2.3.jar</systemPath>
        </dependency>
    </dependencies>

jar 包路径:https://download.csdn.net/download/qq_45463633/86740285

你可能感兴趣的:(java,spring)