Java Code Examples for javax.imageio.ImageIO#write()
The following examples show how to use
javax.imageio.ImageIO#write() .
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: BlueMap File: BlueMapAPIImpl.java License: MIT License | 6 votes |
@Override public String createImage(BufferedImage image, String path) throws IOException { path = path.replaceAll("[^a-zA-Z_\\.\\-\\/]", "_"); String separator = FileSystems.getDefault().getSeparator(); Path webRoot = blueMap.getMainConfig().getWebRoot().toAbsolutePath(); Path webDataRoot = blueMap.getMainConfig().getWebDataPath().toAbsolutePath(); Path imagePath; if (webDataRoot.startsWith(webRoot)) { imagePath = webDataRoot.resolve(Paths.get(IMAGE_ROOT_PATH, path.replace("/", separator) + ".png")).toAbsolutePath(); } else { imagePath = webRoot.resolve("assets").resolve(Paths.get(IMAGE_ROOT_PATH, path.replace("/", separator) + ".png")).toAbsolutePath(); } File imageFile = imagePath.toFile(); imageFile.getParentFile().mkdirs(); imageFile.delete(); imageFile.createNewFile(); if (!ImageIO.write(image, "png", imagePath.toFile())) throw new IOException("The format 'png' is not supported!"); return webRoot.relativize(imagePath).toString().replace(separator, "/"); }
Example 2
Source Project: jdk8u-dev-jdk File: DrawRotatedStringUsingRotatedFont.java License: GNU General Public License v2.0 | 6 votes |
/** * Checks an image color. RED and GREEN are allowed only. */ private static void checkColors(final BufferedImage bi1, final BufferedImage bi2) throws IOException { for (int i = 0; i < SIZE; ++i) { for (int j = 0; j < SIZE; ++j) { final int rgb1 = bi1.getRGB(i, j); final int rgb2 = bi2.getRGB(i, j); if (rgb1 != rgb2 || rgb1 != 0xFFFF0000 && rgb1 != 0xFF00FF00) { ImageIO.write(bi1, "png", new File("image1.png")); ImageIO.write(bi2, "png", new File("image2.png")); throw new RuntimeException("Failed: wrong text location"); } } } }
Example 3
Source Project: selenium File: SnapshotScreenListener.java License: Apache License 2.0 | 6 votes |
@Override public void onException(Throwable throwable, WebDriver driver) { if (Platform.getCurrent().is(Platform.ANDROID)) { // Android Java APIs do not support java.awt return; } String encoded; try { workAroundD3dBugInVista(); Rectangle size = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); BufferedImage image = new Robot().createScreenCapture(size); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(image, "png", outputStream); encoded = Base64.getEncoder().encodeToString(outputStream.toByteArray()); session.attachScreenshot(encoded); } catch (Throwable e) { // Alright. No screen shot. Propagate the original exception } }
Example 4
Source Project: orbit-image-analysis File: SegmenterTest.java License: GNU General Public License v3.0 | 6 votes |
public static void main(String[] args) { BufferedImage cellImage = null; SegmentedImage segmentedImage = null; if (args.length != 3) { System.out.println("parameter imagepath, cellsize and alpha expected"); System.exit(0); } String imagePath = args[0]; int cellSize = Integer.parseInt(args[1]); int alpha = Integer.parseInt(args[2]); try { cellImage = ImageIO.read(new File(imagePath)); BufferedImage mask = BackgroundMaskCreator.getMask(cellImage); segmentedImage = SegmenterFacade.detectCells(cellImage, mask, alpha, cellSize); BufferedImage output = segmentedImage.getPolygonPaintedImage(); ImageIO.write(output, "png", new File("output_" + String.valueOf(cellSize) + "_" + String.valueOf(alpha) + ".png")); } catch (IOException e) { e.printStackTrace(); } }
Example 5
Source Project: hottub File: IncorrectTextSize.java License: GNU General Public License v2.0 | 5 votes |
public static void main(final String[] args) throws IOException { for (int point = 5; point < 11; ++point) { Graphics2D g2d = bi.createGraphics(); g2d.setFont(new Font(Font.DIALOG, Font.PLAIN, point)); g2d.scale(scale, scale); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, width, height); g2d.setColor(Color.green); g2d.drawString(TEXT, 0, 20); int length = g2d.getFontMetrics().stringWidth(TEXT); if (length < 0) { throw new RuntimeException("Negative length"); } for (int i = (length + 1) * scale; i < width; ++i) { for (int j = 0; j < height; ++j) { if (bi.getRGB(i, j) != Color.white.getRGB()) { g2d.drawLine(length, 0, length, height); ImageIO.write(bi, "png", new File("image.png")); System.out.println("length = " + length); System.err.println("Wrong color at x=" + i + ",y=" + j); System.err.println("Color is:" + new Color(bi.getRGB(i, j))); throw new RuntimeException("Test failed."); } } } g2d.dispose(); } }
Example 6
Source Project: TencentKona-8 File: BitDepth.java License: GNU General Public License v2.0 | 5 votes |
private static boolean testPNGByteBinary() throws IOException { int width = 10; int height = 10; File f = new File("BlackStripe.png"); BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY); Graphics2D g = bi.createGraphics(); g.setColor(new Color(255, 255, 255)); g.fillRect(0, 0, width, height); ImageIO.write(bi, "png", f); BufferedImage bi2 = ImageIO.read(f); if (bi2.getWidth() != width || bi2.getHeight() != height) { System.out.println("Dimensions changed!"); return false; } for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int rgb = bi2.getRGB(x, y); if (rgb != 0xffffffff) { System.out.println("Found a non-white pixel!"); return false; } } } f.delete(); return true; }
Example 7
Source Project: kumo File: ImageProcessor.java License: MIT License | 5 votes |
/** *@param fileName is the path of the file * @param imageType can define the type of image * @param width is the resized image's width * @param height is the resized image's height * @return the resized image in ByteArrayInputStream form */ public static InputStream readImage(String fileName, int width, int height, String imageType) throws IOException { final BufferedImage originImage = ImageIO.read(getInputStream(fileName)); final Image scaledImage = originImage.getScaledInstance(width, height, Image.SCALE_SMOOTH); final BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); final Graphics graphics = bufferedImage.getGraphics(); graphics.drawImage(scaledImage, 0, 0, null); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, imageType, outputStream); return new ByteArrayInputStream(outputStream.toByteArray()); }
Example 8
Source Project: dsworkbench File: ScreenshotSaver.java License: Apache License 2.0 | 5 votes |
@Override public void run() { while (true) { if (mScreen != null) { try { Point2D.Double pos = MapPanel.getSingleton().getCurrentPosition(); String first = ""; first = "Zentrum: " + (int) Math.floor(pos.getX()) + "|" + (int) Math.floor(pos.getY()); BufferedImage result = ImageUtils.createCompatibleBufferedImage(mScreen.getWidth(null), mScreen.getHeight(null), BufferedImage.OPAQUE); Graphics2D g2d = (Graphics2D) result.getGraphics(); g2d.drawImage(mScreen, 0, 0, null); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f)); FontMetrics fm = g2d.getFontMetrics(); Rectangle2D firstBounds = fm.getStringBounds(first, g2d); String second = "Erstellt mit DS Workbench " + Constants.VERSION + Constants.VERSION_ADDITION; Rectangle2D secondBounds = fm.getStringBounds(second, g2d); g2d.setColor(Constants.DS_BACK_LIGHT); g2d.fill3DRect(0, (int) (result.getHeight() - firstBounds.getHeight() - secondBounds.getHeight() - 9), (int) (secondBounds.getWidth() + 6), (int) (firstBounds.getHeight() + secondBounds.getHeight() + 9), true); g2d.setColor(Color.BLACK); g2d.drawString(first, 3, (int) (result.getHeight() - firstBounds.getHeight() - secondBounds.getHeight() - firstBounds.getY() - 6)); g2d.drawString(second, 3, (int) (result.getHeight() - secondBounds.getHeight() - secondBounds.getY() - 3)); g2d.dispose(); ImageIO.write(result, mTargetType, fTargetFile); DSWorkbenchMainFrame.getSingleton().fireMapShotDoneEvent(); } catch (Exception e) { DSWorkbenchMainFrame.getSingleton().fireMapShotFailedEvent(); } mScreen = null; } try { Thread.sleep(1000); } catch (Exception ignored) { } } }
Example 9
Source Project: openjdk-jdk9 File: DrawRect.java License: GNU General Public License v2.0 | 5 votes |
private static void test(final BufferedImage gold, final BufferedImage bi) throws IOException { for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { if (gold.getRGB(x, y) != bi.getRGB(x, y)) { ImageIO.write(gold, "png", new File("gold.png")); ImageIO.write(bi, "png", new File("image.png")); throw new RuntimeException("wrong color"); } } } }
Example 10
Source Project: pdfbox-layout File: ExampleTest.java License: MIT License | 5 votes |
protected static void comparePdfs(final File newPdf, InputStream toCompareTo) throws IOException, AssertionError { try (PDDocument currentDoc = PDDocument.load(newPdf); PDDocument oldDoc = PDDocument.load(toCompareTo)) { if (currentDoc.getNumberOfPages() != oldDoc.getNumberOfPages()) { throw new AssertionError(String.format( "expected %d pages, but is %d", oldDoc.getNumberOfPages(), currentDoc.getNumberOfPages())); } for (int i = 0; i < oldDoc.getNumberOfPages(); i++) { BufferedImage currentPageImg = toImage(currentDoc, i); BufferedImage oldPageImg = toImage(oldDoc, i); BufferedImage diff = compareImage(currentPageImg, oldPageImg); if (diff != null) { File diffFile = new File(newPdf.getAbsoluteFile() + ".diff.png"); ImageIO.write(diff, "png", diffFile); throw new AssertionError(String.format( "page %d different, wrote diff image %s", i + 1, diffFile)); } } } }
Example 11
Source Project: openjdk-jdk8u-backup File: IncorrectClipXorModeSW2Surface.java License: GNU General Public License v2.0 | 5 votes |
private static void validate(BufferedImage bi, BufferedImage goldbi) throws IOException { for (int x = 0; x < bi.getWidth(); ++x) { for (int y = 0; y < bi.getHeight(); ++y) { if (goldbi.getRGB(x, y) != bi.getRGB(x, y)) { ImageIO.write(bi, "png", new File("actual.png")); ImageIO.write(goldbi, "png", new File("expected.png")); throw new RuntimeException("Test failed."); } } } }
Example 12
Source Project: tephra File: PptxReaderImpl.java License: MIT License | 5 votes |
private String write(MediaWriter mediaWriter, BufferedImage bufferedImage, String fileName) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "PNG", byteArrayOutputStream); byteArrayOutputStream.close(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); String url = mediaWriter.write(MediaType.Png, fileName, byteArrayInputStream); byteArrayInputStream.close(); return url; }
Example 13
Source Project: jdk8u-jdk File: DrawRotatedString.java License: GNU General Public License v2.0 | 5 votes |
private static void verify(BufferedImage bi) throws IOException { for (int i = 0; i < SIZE; ++i) { for (int j = 0; j < 99; ++j) { //Text should not appear before 100 if (bi.getRGB(i, j) != Color.RED.getRGB()) { ImageIO.write(bi, "png", new File("image.png")); throw new RuntimeException("Failed: wrong text location"); } } } }
Example 14
Source Project: orbit-image-analysis File: TileSizeWrapper.java License: GNU General Public License v3.0 | 5 votes |
public static void main(String[] args) throws Exception { String testImage = "D:\\pic\\Hamamatsu\\bloodsmear.ndpi"; RawDataFile rdf = DALConfig.getImageProvider().LoadRawDataFile(6184134); IOrbitImage oi = DALConfig.getImageProvider().createOrbitImage(rdf,0); //try (OrbitImageBioformats oi = new OrbitImageBioformats(testImage,2,0,null)) { System.out.println("tileSize before: " + oi.getTileWidth() + " x " + oi.getTileHeight()); TileSizeWrapper tw = new TileSizeWrapper(oi, 512, 512); OrbitTiledImage2 oit2 = new OrbitTiledImageIOrbitImage(tw,0); System.out.println("tileSize after: " + oit2.getTileWidth() + " x " + oit2.getTileHeight()); for (int tx=20; tx<23; tx++) for (int ty=20; ty<23; ty++) { WritableRaster raster = (WritableRaster)oit2.getTile(tx, ty); //59,10 //System.out.println("tx x ty: "+tx+" x "+ty+" "+ "wxh: " + raster.getWidth() + " x " + raster.getHeight()+" scanlinestride: "+((ByteInterleavedRaster)raster).getScanlineStride()+" oit2: "+((PixelInterleavedSampleModel)oit2.getSampleModel()).getScanlineStride()); raster = (WritableRaster) raster.createTranslatedChild(0, 0); BufferedImage bi = new BufferedImage(oit2.getColorModel(), raster, false, null); ImageIO.write(bi, "png", new File("d:/NoBackup/a/tile"+ tx+"x"+ty+".png")); } } oi.close(); }
Example 15
Source Project: constellation File: GlyphManagerBI.java License: Apache License 2.0 | 4 votes |
@Override public void writeGlyphBuffer(final int page, final OutputStream out) throws IOException { final BufferedImage img = textureBuffer.get(page); ImageIO.write(img, "png", out); }
Example 16
Source Project: openjdk-jdk9 File: CrashNaNTest.java License: GNU General Public License v2.0 | 4 votes |
private static void testDrawComplexAt() { final int width = 400; final int height = 400; final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d = (Graphics2D) image.getGraphics(); try { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, width, height); final Path2D.Double path = new Path2D.Double(); path.moveTo(100, 100); for (int i = 0; i < 20000; i++) { path.lineTo(110 + 0.01 * i, 110); path.lineTo(111 + 0.01 * i, 100); } path.lineTo(NaN, 200); path.lineTo(200, 200); path.lineTo(200, NaN); path.lineTo(300, 300); path.lineTo(NaN, NaN); path.lineTo(100, 200); path.closePath(); final Path2D.Double path2 = new Path2D.Double(); path2.moveTo(0, 0); path2.lineTo(100, height); path2.lineTo(0, 200); path2.closePath(); // Define an non-uniform transform: g2d.scale(0.5, 1.0); g2d.rotate(Math.PI / 31); g2d.setColor(Color.BLACK); g2d.draw(path); g2d.draw(path2); if (SAVE_IMAGE) { try { final File file = new File("CrashNaNTest-draw.png"); System.out.println("Writing file: " + file.getAbsolutePath()); ImageIO.write(image, "PNG", file); } catch (IOException ex) { System.out.println("Writing file failure:"); ex.printStackTrace(); } } // Check image on few pixels: final Raster raster = image.getData(); checkPixelNotWhite(raster, 40, 210); checkPixelNotWhite(raster, 44, 110); checkPixelNotWhite(raster, 60, 120); checkPixelNotWhite(raster, 89, 219); checkPixelNotWhite(raster, 28, 399); checkPixelNotWhite(raster, 134, 329); } finally { g2d.dispose(); } }
Example 17
Source Project: jdk8u_jdk File: OutputImageTests.java License: GNU General Public License v2.0 | 4 votes |
void initContents(OutputStream out) throws IOException { ImageIO.write(image, format, out); }
Example 18
Source Project: JavaLib File: ImageUtils.java License: MIT License | 4 votes |
/** * 图片裁剪 * @param filePath 原图片 * @param width 宽 * @param height 高 * @return BufferedImage * @throws Exception 异常 */ public static BufferedImage clipping(String filePath, int width, int height) throws Exception { BufferedImage buffer = ImageIO.read(new File(filePath)); /* * 核心算法,计算图片的压缩比 */ int w= buffer.getWidth(); int h=buffer.getHeight(); double ratiox = 1.0d; double ratioy = 1.0d; ratiox= w * ratiox / width; ratioy= h * ratioy / height; if( ratiox >= 1){ if(ratioy < 1){ ratiox = height * 1.0 / h; }else{ if(ratiox > ratioy){ ratiox = height * 1.0 / h; }else{ ratiox = width * 1.0 / w; } } }else{ if(ratioy < 1){ if(ratiox > ratioy){ ratiox = height * 1.0 / h; }else{ ratiox = width * 1.0 / w; } }else{ ratiox = width * 1.0 / w; } } /* * 对于图片的放大或缩小倍数计算完成,ratiox大于1,则表示放大,否则表示缩小 */ AffineTransformOp op = new AffineTransformOp(AffineTransform .getScaleInstance(ratiox, ratiox), null); buffer = op.filter(buffer, null); //从放大的图像中心截图 buffer = buffer.getSubimage((buffer.getWidth()-width)/2, (buffer.getHeight() - height) / 2, width, height); // 将 buffer 转成 图片 ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(buffer, "jpg", out); return buffer; }
Example 19
Source Project: SpringAll File: ValidateController.java License: MIT License | 4 votes |
@GetMapping("/code/image") public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException { ImageCode imageCode = createImageCode(); sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_IMAGE_CODE, imageCode); ImageIO.write(imageCode.getImage(), "jpeg", response.getOutputStream()); }
Example 20
Source Project: MaxKey File: QRCode.java License: Apache License 2.0 | 3 votes |
/** * As {@link #writeToStream(BitMatrix, String, OutputStream)}, but allows customization of the output. * * @param matrix {@link BitMatrix} to write * @param format image format * @param stream {@link OutputStream} to write image to * @param config output configuration * @throws IOException if writes to the stream fail */ public static void writeToStream(BitMatrix matrix, String format, OutputStream stream, QRCodeConfig config) throws IOException { BufferedImage image = toBufferedImage(matrix, config); if (!ImageIO.write(image, format, stream)) { throw new IOException("Could not write an image of format " + format); } }