summaryrefslogblamecommitdiffstats
path: root/src/main/java/org/openslx/satserver/util/Ppm.java
blob: 29491d7971bdc5ac2704fea9f9abcc71e9e2f80e (plain) (tree)



















































                                                                                                                                     
package org.openslx.satserver.util;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class Ppm
{

	/**
	 * Save image as ppm file.
	 * 
	 * @param inImage BufferedImage to save
	 * @param fName file name to save as
	 * @param white
	 * @throws IOException
	 */
	public static boolean write( BufferedImage inImage, String fName, Color transparent ) throws IOException
	{
		FileOutputStream bw = null;
		final int tr = transparent.getRed();
		final int tg = transparent.getGreen();
		final int tb = transparent.getBlue();
		try {
			File theFile = new File( fName );
			bw = new FileOutputStream( theFile );
			bw.write( "P6\n".getBytes( StandardCharsets.UTF_8 ) );
			bw.write( ( inImage.getWidth() + " " + inImage.getHeight() + " 255\n" ).getBytes( StandardCharsets.UTF_8 ) );

			for ( int y = 0; y < inImage.getHeight(); ++y ) {
				for ( int x = 0; x < inImage.getWidth(); ++x ) {
					int color = inImage.getRGB( x, y );
					int alpha = ( color >>> 24 ) & 0xFF;
					int red = ( color >>> 16 ) & 0xFF;
					int green = ( color >>> 8 ) & 0xFF;
					int blue = ( color ) & 0xFF;
					bw.write( ( ( red * alpha ) + ( tr * ( 255 - alpha ) ) ) / 255 );
					bw.write( ( ( green * alpha ) + ( tg * ( 255 - alpha ) ) ) / 255 );
					bw.write( ( ( blue * alpha ) + ( tb * ( 255 - alpha ) ) ) / 255 );
				}
			}
			bw.close();
		} finally {
			Util.multiClose( bw );
		}
		return true;
	}

}