PNG转GIF

PNG转GIF,并保留透明部分

	public static void convertPNG(File file, File outfile){
		List<BufferedImage> images = new ArrayList<BufferedImage>();
    try{
      Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName("png");
			ImageReader imageReader = (ImageReader)imageReaders.next();
			imageReader.setInput(ImageIO.createImageInputStream(file));
			
			for(int i = 0;true;++i){
				try{
					BufferedImage aa=imageReader.read(i);
					images.add(aa);
				}catch (Exception e) {
					break;
				}
			}
			
			BufferedImage[] bufimages= images.toArray(new BufferedImage[images.size()]);
			Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("gif");
			ImageWriter imageWriter = (ImageWriter)imageWriters.next();
			outfile.delete();
			imageWriter.setOutput(ImageIO.createImageOutputStream(outfile));
			if(imageWriter.canWriteSequence()){
				imageWriter.prepareWriteSequence(null);
				for(int i = 0;i < bufimages.length;++i){
					imageWriter.writeToSequence(new IIOImage(bufimages[i],null,null),null);
				}
				imageWriter.endWriteSequence();
			}else{
				for(int i = 0;i < bufimages.length;++i){
					imageWriter.write(bufimages[i]);
				}
			}
		}catch (Exception   e)   {  
			e.printStackTrace();  
		}

	}

你可能感兴趣的:(png)