Here you can find the source of toByteArray(final BufferedImage image, final String format)
Parameter | Description |
---|---|
image | The image to convert |
format | The image format |
public static byte[] toByteArray(final BufferedImage image, final String format)
//package com.java2s; /******************************************************************************* * Copyright 2016 Johannes Boczek//from w ww. ja v a 2 s. c o m * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; public class Main { /** * Converts an image to a byte array. * @param image The image to convert * @param format The image format * @return The image data */ public static byte[] toByteArray(final BufferedImage image, final String format) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ImageIO.write(image, "PNG", out); } catch (final IOException ex) { ex.printStackTrace(); } final byte[] data = out.toByteArray(); return data; } /** * Converts an image to a byte array. * Uses the PNG image format. * @param image The image to convert * @return The image data */ public static byte[] toByteArray(final BufferedImage image) { return toByteArray(image, "PNG"); } /** * Converts an image to a byte array. * Uses the JPEG image format. * The quality can be between 1 (best) and 0 (highest compression) * @param image The image that should be converted * @param quality The quality of the image * @return The image as a byte array */ public static byte[] toByteArray(final BufferedImage image, final float quality) { final Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("JPG"); final ImageWriter writer = writers.next(); final ImageWriteParam param = writer.getDefaultWriteParam(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(quality); try { final ImageOutputStream imageOut = ImageIO.createImageOutputStream(out); writer.setOutput(imageOut); writer.write(image); return out.toByteArray(); } catch (final IOException ex) { ex.printStackTrace(); } return null; } }