Path: blob/master/SLICK_HOME/src/org/newdawn/slick/imageout/ImageIOWriter.java
1461 views
package org.newdawn.slick.imageout;12import java.awt.Point;3import java.awt.color.ColorSpace;4import java.awt.image.BufferedImage;5import java.awt.image.ColorModel;6import java.awt.image.ComponentColorModel;7import java.awt.image.DataBuffer;8import java.awt.image.DataBufferByte;9import java.awt.image.PixelInterleavedSampleModel;10import java.awt.image.Raster;11import java.awt.image.WritableRaster;12import java.io.IOException;13import java.io.OutputStream;14import java.nio.ByteBuffer;1516import javax.imageio.ImageIO;1718import org.newdawn.slick.Color;19import org.newdawn.slick.Image;2021/**22* A utility to write a Slick image out using ImageIO23*24* @author Jon25*/26public class ImageIOWriter implements ImageWriter {27/**28* @see org.newdawn.slick.imageout.ImageWriter#saveImage(org.newdawn.slick.Image,29* java.lang.String, java.io.OutputStream, boolean)30*/31public void saveImage(Image image, String format, OutputStream output, boolean hasAlpha)32throws IOException {33// conver the image into a byte buffer by reading each pixel in turn34int len = 4 * image.getWidth() * image.getHeight();35if (!hasAlpha) {36len = 3 * image.getWidth() * image.getHeight();37}3839ByteBuffer out = ByteBuffer.allocate(len);40Color c;4142for (int y = 0; y < image.getHeight(); y++) {43for (int x = 0; x < image.getWidth(); x++) {44c = image.getColor(x, y);4546out.put((byte) (c.r * 255.0f));47out.put((byte) (c.g * 255.0f));48out.put((byte) (c.b * 255.0f));49if (hasAlpha) {50out.put((byte) (c.a * 255.0f));51}52}53}5455// create a raster of the correct format and fill it with our buffer56DataBufferByte dataBuffer = new DataBufferByte(out.array(), len);5758PixelInterleavedSampleModel sampleModel;5960ColorModel cm;6162if (hasAlpha) {63int[] offsets = { 0, 1, 2, 3 };64sampleModel = new PixelInterleavedSampleModel(65DataBuffer.TYPE_BYTE, image.getWidth(), image.getHeight(), 4,664 * image.getWidth(), offsets);6768cm = new ComponentColorModel(ColorSpace69.getInstance(ColorSpace.CS_sRGB), new int[] { 8, 8, 8, 8 },70true, false, ComponentColorModel.TRANSLUCENT,71DataBuffer.TYPE_BYTE);72} else {73int[] offsets = { 0, 1, 2};74sampleModel = new PixelInterleavedSampleModel(75DataBuffer.TYPE_BYTE, image.getWidth(), image.getHeight(), 3,763 * image.getWidth(), offsets);7778cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),79new int[] {8,8,8,0},80false,81false,82ComponentColorModel.OPAQUE,83DataBuffer.TYPE_BYTE);84}85WritableRaster raster = Raster.createWritableRaster(sampleModel, dataBuffer, new Point(0, 0));8687// finally create the buffered image based on the data from the texture88// and spit it through to ImageIO89BufferedImage img = new BufferedImage(cm, raster, false, null);9091ImageIO.write(img, format, output);92}93}949596