下面列出了javax.imageio.stream.ImageOutputStream#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageWriter writer = ictx.writer;
final BufferedImage image = ictx.image;
do {
try {
ImageOutputStream ios = ictx.createImageOutputStream();
writer.setOutput(ios);
writer.write(image);
writer.reset();
ios.close();
ictx.closeOriginalStream();
} catch (IOException e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
private static long saveImage(final BufferedImage image,
final ImageWriter writer,
final ImageWriteParam writerParams,
final String mode,
final String suffix) throws IOException
{
final File imgFile = new File("WriterCompressionTest-"
+ mode + '.' + suffix);
System.out.println("Writing file: " + imgFile.getAbsolutePath());
final ImageOutputStream imgOutStream
= ImageIO.createImageOutputStream(new FileOutputStream(imgFile));
try {
writer.setOutput(imgOutStream);
writer.write(null, new IIOImage(image, null, null), writerParams);
} finally {
imgOutStream.close();
}
return imgFile.length();
}
protected File writeImageWithHist(BufferedImage bi) throws IOException {
File f = File.createTempFile("hist_", ".png", new File("."));
ImageWriter writer = ImageIO.getImageWritersByFormatName("PNG").next();
ImageOutputStream ios = ImageIO.createImageOutputStream(f);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
ImageTypeSpecifier type = new ImageTypeSpecifier(bi);
IIOMetadata imgMetadata = writer.getDefaultImageMetadata(type, param);
/* add hIST node to image metadata */
imgMetadata = upgradeMetadata(imgMetadata, bi);
IIOImage iio_img = new IIOImage(bi,
null, // no thumbnails
imgMetadata);
writer.write(iio_img);
ios.flush();
ios.close();
return f;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageWriter writer = ictx.writer;
final BufferedImage image = ictx.image;
do {
try {
ImageOutputStream ios = ictx.createImageOutputStream();
writer.setOutput(ios);
writer.write(image);
writer.reset();
ios.close();
ictx.closeOriginalStream();
} catch (IOException e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageWriter writer = ictx.writer;
final BufferedImage image = ictx.image;
do {
try {
ImageOutputStream ios = ictx.createImageOutputStream();
writer.setOutput(ios);
writer.write(image);
writer.reset();
ios.close();
ictx.closeOriginalStream();
} catch (IOException e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
private Icon getIcon(ImageWriter imageWriter) throws IOException {
GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gDev = gEnv.getDefaultScreenDevice();
GraphicsConfiguration gConfig = gDev.getDefaultConfiguration();
BufferedImage bufferedImage = gConfig.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
bufferedImage.setRGB(0, 0, width, height, array, 0, width);
OutputStream out = new ByteArrayOutputStream();
ImageOutputStream imageOut = new MemoryCacheImageOutputStream(out);
imageWriter.setOutput(imageOut);
try {
imageWriter.write(bufferedImage);
}
finally {
imageOut.close();
}
Icon icon = new ImageIcon(bufferedImage);
return icon;
}
public static byte[] getImageBytes(Image image, String type) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedImage bufImage = convertToBufferedImage(image);
ImageWriter writer = null;
Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(type);
if (i.hasNext()) {
writer = i.next();
}
if (writer != null) {
ImageOutputStream stream = null;
stream = ImageIO.createImageOutputStream(baos);
writer.setOutput(stream);
writer.write(bufImage);
stream.close();
return baos.toByteArray();
}
return null;
}
@Override
public void saveToFile(TexturePacker.Settings settings, BufferedImage image, File file) throws IOException {
ImageOutputStream ios = null;
try {
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
newImage.getGraphics().drawImage(image, 0, 0, null);
image = newImage;
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = writers.next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
ios = ImageIO.createImageOutputStream(file);
writer.setOutput(ios);
writer.write(null, new IIOImage(image, null, null), param);
} finally {
if (ios != null) {
try { ios.close(); } catch (Exception ignored) { }
}
}
}
private void writeInternal(BufferedImage image, MediaType contentType, OutputStream body)
throws IOException, HttpMessageNotWritableException {
ImageOutputStream imageOutputStream = null;
ImageWriter imageWriter = null;
try {
Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(contentType.toString());
if (imageWriters.hasNext()) {
imageWriter = imageWriters.next();
ImageWriteParam iwp = imageWriter.getDefaultWriteParam();
process(iwp);
imageOutputStream = createImageOutputStream(body);
imageWriter.setOutput(imageOutputStream);
imageWriter.write(null, new IIOImage(image, null, null), iwp);
}
else {
throw new HttpMessageNotWritableException(
"Could not find javax.imageio.ImageWriter for Content-Type [" + contentType + "]");
}
}
finally {
if (imageWriter != null) {
imageWriter.dispose();
}
if (imageOutputStream != null) {
try {
imageOutputStream.close();
}
catch (IOException ex) {
// ignore
}
}
}
}
/**
* Writes an image using an arbitrary <code>ImageWriter</code>
* that supports the given format to a <code>File</code>. If
* there is already a <code>File</code> present, its contents are
* discarded.
*
* @param im a <code>RenderedImage</code> to be written.
* @param formatName a <code>String</code> containing the informal
* name of the format.
* @param output a <code>File</code> to be written to.
*
* @return <code>false</code> if no appropriate writer is found.
*
* @exception IllegalArgumentException if any parameter is
* <code>null</code>.
* @exception IOException if an error occurs during writing.
*/
public static boolean write(RenderedImage im,
String formatName,
File output) throws IOException {
if (output == null) {
throw new IllegalArgumentException("output == null!");
}
ImageOutputStream stream = null;
ImageWriter writer = getWriter(im, formatName);
if (writer == null) {
/* Do not make changes in the file system if we have
* no appropriate writer.
*/
return false;
}
try {
output.delete();
stream = createImageOutputStream(output);
} catch (IOException e) {
throw new IIOException("Can't create output stream!", e);
}
try {
return doWrite(im, writer, stream);
} finally {
stream.close();
}
}
private static void writeTo(File f, ITXtTest t) {
BufferedImage src = createBufferedImage();
try {
ImageOutputStream imageOutputStream =
ImageIO.createImageOutputStream(f);
ImageTypeSpecifier imageTypeSpecifier =
new ImageTypeSpecifier(src);
ImageWriter imageWriter =
ImageIO.getImageWritersByFormatName("PNG").next();
imageWriter.setOutput(imageOutputStream);
IIOMetadata m =
imageWriter.getDefaultImageMetadata(imageTypeSpecifier, null);
String format = m.getNativeMetadataFormatName();
Node root = m.getAsTree(format);
IIOMetadataNode iTXt = t.getNode();
root.appendChild(iTXt);
m.setFromTree(format, root);
imageWriter.write(new IIOImage(src, null, m));
imageOutputStream.close();
System.out.println("Writing done.");
} catch (Throwable e) {
throw new RuntimeException("Writing test failed.", e);
}
}
private static void writeTo(File f, ITXtTest t) {
BufferedImage src = createBufferedImage();
try {
ImageOutputStream imageOutputStream =
ImageIO.createImageOutputStream(f);
ImageTypeSpecifier imageTypeSpecifier =
new ImageTypeSpecifier(src);
ImageWriter imageWriter =
ImageIO.getImageWritersByFormatName("PNG").next();
imageWriter.setOutput(imageOutputStream);
IIOMetadata m =
imageWriter.getDefaultImageMetadata(imageTypeSpecifier, null);
String format = m.getNativeMetadataFormatName();
Node root = m.getAsTree(format);
IIOMetadataNode iTXt = t.getNode();
root.appendChild(iTXt);
m.setFromTree(format, root);
imageWriter.write(new IIOImage(src, null, m));
imageOutputStream.close();
System.out.println("Writing done.");
} catch (Throwable e) {
throw new RuntimeException("Writing test failed.", e);
}
}
private void write(File f, boolean subsample) throws IOException {
ImageOutputStream ios = ImageIO.createImageOutputStream(f);
writer.setOutput(ios);
ImageWriteParam p = writer.getDefaultWriteParam();
if (subsample) {
p.setSourceSubsampling(subSampleX, subSampleY, 0, 0);
}
writer.write(null, new IIOImage(img, null, null), p);
ios.close();
writer.reset();
}
private static void writeTo(File f, ITXtTest t) {
BufferedImage src = createBufferedImage();
try {
ImageOutputStream imageOutputStream =
ImageIO.createImageOutputStream(f);
ImageTypeSpecifier imageTypeSpecifier =
new ImageTypeSpecifier(src);
ImageWriter imageWriter =
ImageIO.getImageWritersByFormatName("PNG").next();
imageWriter.setOutput(imageOutputStream);
IIOMetadata m =
imageWriter.getDefaultImageMetadata(imageTypeSpecifier, null);
String format = m.getNativeMetadataFormatName();
Node root = m.getAsTree(format);
IIOMetadataNode iTXt = t.getNode();
root.appendChild(iTXt);
m.setFromTree(format, root);
imageWriter.write(new IIOImage(src, null, m));
imageOutputStream.close();
System.out.println("Writing done.");
} catch (Throwable e) {
throw new RuntimeException("Writing test failed.", e);
}
}
private static void writeWithCompression(BufferedImage src,
String compression) throws IOException
{
System.out.println("Compression: " + compression);
ImageWriter writer = ImageIO.getImageWritersByFormatName("BMP").next();
if (writer == null) {
throw new RuntimeException("Test failed: no bmp writer available");
}
File fout = File.createTempFile(compression + "_", ".bmp",
new File("."));
ImageOutputStream ios = ImageIO.createImageOutputStream(fout);
writer.setOutput(ios);
BMPImageWriteParam param = (BMPImageWriteParam)
writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType(compression);
param.setTopDown(true);
writer.write(null, new IIOImage(src, null, null), param);
writer.dispose();
ios.flush();
ios.close();
BufferedImage dst = ImageIO.read(fout);
verify(dst);
}
public Base64Data print(Image v) {
ByteArrayOutputStreamEx imageData = new ByteArrayOutputStreamEx();
XMLSerializer xs = XMLSerializer.getInstance();
String mimeType = xs.getXMIMEContentType();
if(mimeType==null || mimeType.startsWith("image/*"))
// because PNG is lossless, it's a good default
//
// mime type can be a range, in which case we can't just pass that
// to ImageIO.getImageWritersByMIMEType, so here I'm just assuming
// the default of PNG. Not sure if this is complete.
mimeType = "image/png";
try {
Iterator<ImageWriter> itr = ImageIO.getImageWritersByMIMEType(mimeType);
if(itr.hasNext()) {
ImageWriter w = itr.next();
ImageOutputStream os = ImageIO.createImageOutputStream(imageData);
w.setOutput(os);
w.write(convertToBufferedImage(v));
os.close();
w.dispose();
} else {
// no encoder
xs.handleEvent(new ValidationEventImpl(
ValidationEvent.ERROR,
Messages.NO_IMAGE_WRITER.format(mimeType),
xs.getCurrentLocation(null) ));
// TODO: proper error reporting
throw new RuntimeException("no encoder for MIME type "+mimeType);
}
} catch (IOException e) {
xs.handleError(e);
// TODO: proper error reporting
throw new RuntimeException(e);
}
Base64Data bd = new Base64Data();
imageData.set(bd,mimeType);
return bd;
}
private static void writeWithCompression(BufferedImage src,
String compression) throws IOException
{
System.out.println("Compression: " + compression);
ImageWriter writer = ImageIO.getImageWritersByFormatName("BMP").next();
if (writer == null) {
throw new RuntimeException("Test failed: no bmp writer available");
}
File fout = File.createTempFile(compression + "_", ".bmp",
new File("."));
ImageOutputStream ios = ImageIO.createImageOutputStream(fout);
writer.setOutput(ios);
BMPImageWriteParam param = (BMPImageWriteParam)
writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType(compression);
param.setTopDown(true);
writer.write(null, new IIOImage(src, null, null), param);
writer.dispose();
ios.flush();
ios.close();
BufferedImage dst = ImageIO.read(fout);
verify(dst);
}
/**
* Writes an image using an arbitrary {@code ImageWriter}
* that supports the given format to an {@code OutputStream}.
*
* <p> This method <em>does not</em> close the provided
* {@code OutputStream} after the write operation has completed;
* it is the responsibility of the caller to close the stream, if desired.
*
* <p> The current cache settings from {@code getUseCache} and
* {@code getCacheDirectory} will be used to control caching.
*
* @param im a {@code RenderedImage} to be written.
* @param formatName a {@code String} containing the informal
* name of the format.
* @param output an {@code OutputStream} to be written to.
*
* @return {@code false} if no appropriate writer is found.
*
* @exception IllegalArgumentException if any parameter is
* {@code null}.
* @exception IOException if an error occurs during writing or when not
* able to create required ImageOutputStream.
*/
public static boolean write(RenderedImage im,
String formatName,
OutputStream output) throws IOException {
if (output == null) {
throw new IllegalArgumentException("output == null!");
}
ImageOutputStream stream = createImageOutputStream(output);
if (stream == null) {
throw new IIOException("Can't create an ImageOutputStream!");
}
try {
return doWrite(im, getWriter(im, formatName), stream);
} finally {
stream.close();
}
}
private void test(final ImageWriter writer) throws IOException {
// Image initialization
final BufferedImage imageWrite = new BufferedImage(WIDTH, HEIGHT,
TYPE_BYTE_BINARY);
final Graphics2D g = imageWrite.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.dispose();
// File initialization
final File file = File.createTempFile("temp", ".img");
file.deleteOnExit();
final FileOutputStream fos = new SkipWriteOnAbortOutputStream(file);
final ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
writer.setOutput(ios);
writer.addIIOWriteProgressListener(this);
// This write will be aborted, and file will not be touched
writer.write(imageWrite);
if (!isStartedCalled) {
throw new RuntimeException("Started should be called");
}
if (!isProgressCalled) {
throw new RuntimeException("Progress should be called");
}
if (!isAbortCalled) {
throw new RuntimeException("Abort should be called");
}
if (isCompleteCalled) {
throw new RuntimeException("Complete should not be called");
}
// Flush aborted data
ios.flush();
// This write should be completed successfully and the file should
// contain correct image data.
abortFlag = false;
isAbortCalled = false;
isCompleteCalled = false;
isProgressCalled = false;
isStartedCalled = false;
writer.write(imageWrite);
if (!isStartedCalled) {
throw new RuntimeException("Started should be called");
}
if (!isProgressCalled) {
throw new RuntimeException("Progress should be called");
}
if (isAbortCalled) {
throw new RuntimeException("Abort should not be called");
}
if (!isCompleteCalled) {
throw new RuntimeException("Complete should be called");
}
writer.dispose();
ios.close();
// Validates content of the file.
final BufferedImage imageRead = ImageIO.read(file);
for (int x = 0; x < WIDTH; ++x) {
for (int y = 0; y < HEIGHT; ++y) {
if (imageRead.getRGB(x, y) != imageWrite.getRGB(x, y)) {
throw new RuntimeException("Test failed.");
}
}
}
}
public BMPSubsamplingTest() throws IOException {
ImageWriter writer =
ImageIO.getImageWritersByFormatName(format).next();
ImageWriteParam wparam = writer.getDefaultWriteParam();
wparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
String[] types = wparam.getCompressionTypes();
for (int t = 0; t < img_types.length; t++) {
int img_type = img_types[t];
System.out.println("Test for " + getImageTypeName(img_type));
BufferedImage image = getTestImage(img_type);
ImageTypeSpecifier specifier = new ImageTypeSpecifier(image);
if (!writer.getOriginatingProvider().canEncodeImage(specifier)) {
System.out.println("Writer does not support encoding this buffered image type.");
continue;
}
for(int i=0; i<types.length; i++) {
if ("BI_JPEG".equals(types[i])) {
// exclude BI_JPEG from automatic test
// due to color diffusion effect on the borders.
continue;
}
if (canEncodeImage(types[i], specifier, img_type)) {
System.out.println("compression type: " + types[i] +
" Supported for " + getImageTypeName(img_type));
} else {
System.out.println("compression type: " + types[i] +
" NOT Supported for " + getImageTypeName(img_type));
continue;
}
ImageWriteParam imageWriteParam = getImageWriteParam(writer, types[i]);
imageWriteParam.setSourceSubsampling(srcXSubsampling,
srcYSubsampling,
0, 0);
File outputFile = new File("subsampling_test_" +
getImageTypeName(img_type) + "__" +
types[i] + ".bmp");
ImageOutputStream ios =
ImageIO.createImageOutputStream(outputFile);
writer.setOutput(ios);
IIOImage iioImg = new IIOImage(image, null, null);
writer.write(null, iioImg, imageWriteParam);
ios.flush();
ios.close();
BufferedImage outputImage = ImageIO.read(outputFile);
checkTestImage(outputImage);
}
}
}