List of usage examples for javax.imageio ImageReader read
public BufferedImage read(int imageIndex) throws IOException
From source file:com.qwazr.extractor.parser.ImageParser.java
@Override public void parseContent(final MultivaluedMap<String, String> parameters, final Path path, final String extension, final String mimeType, final ParserResultBuilder resultBuilder) throws Exception { final ImagePHash imgPhash = new ImagePHash(); try (final ImageInputStream in = ImageIO.createImageInputStream(path.toFile())) { final Iterator<ImageReader> readers = ImageIO.getImageReaders(in); if (readers.hasNext()) { ParserFieldsBuilder result = resultBuilder.newDocument(); ImageReader reader = readers.next(); resultBuilder.metas().set(MIME_TYPE, "image/" + reader.getFormatName().toLowerCase()); try { reader.setInput(in);/*from www .j a va2 s . c o m*/ result.add(WIDTH, reader.getWidth(0)); result.add(HEIGHT, reader.getHeight(0)); result.add(FORMAT, reader.getFormatName()); result.add(PHASH, imgPhash.getHash(reader.read(0))); IIOMetadata metadata = reader.getImageMetadata(0); if (metadata != null) { String[] names = metadata.getMetadataFormatNames(); if (names != null) for (String name : names) browseNodes("META", metadata.getAsTree(name), result); } } finally { reader.dispose(); } } } }
From source file:org.paxle.gui.impl.MenuManager.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { if (req.getParameter("icon") != null) { String iconURL = req.getParameter("icon"); BufferedImage img = null; String fileSuffix = null; int idx = iconURL.lastIndexOf("."); if (idx != -1) fileSuffix = iconURL.substring(idx + 1); if (fileSuffix != null) { Iterator<ImageReader> readers = ImageIO.getImageReadersBySuffix(fileSuffix); while (readers.hasNext() && img == null) { ImageReader reader = readers.next(); InputStream input = null; try { input = new URL(iconURL).openStream(); reader.setInput(ImageIO.createImageInputStream(input)); img = reader.read(0); } catch (Exception e) { this.log("Unable to read image from " + iconURL, e); } finally { if (input != null) input.close();//from w ww . jav a2s. c o m } } } else { img = ImageIO.read(new URL(iconURL)); } if (img != null) { response.setHeader("Content-Type", "image/png"); ImageIO.write(img, "png", response.getOutputStream()); } else { response.sendError(404); } } }
From source file:com.gargoylesoftware.htmlunit.html.HtmlImage.java
/** * Saves this image as the specified file. * @param file the file to save to// w w w . j av a 2 s .c o m * @throws IOException if an IO error occurs */ public void saveAs(final File file) throws IOException { final ImageReader reader = getImageReader(); ImageIO.write(reader.read(0), reader.getFormatName(), file); }
From source file:org.geoserver.wcs.GetCoverageTest.java
/** * This tests just ended up throwing an exception as the coverage being encoded * was too large due to a bug in the scales estimation * /*from w w w .jav a 2 s.com*/ * @throws Exception */ @Test public void testRotatedGet() throws Exception { String request = "wcs?&service=WCS&request=GetCoverage&version=1.1.1&identifier=RotatedCad&BoundingBox=7.7634071540971386,45.14712131948007,7.76437367395267,45.14764567708965,urn:ogc:def:crs:OGC:1.3:CRS84&Format=image/tiff"; MockHttpServletResponse response = getAsServletResponse(request); // parse the multipart, check there are two parts Multipart multipart = getMultipart(response); assertEquals(2, multipart.getCount()); BodyPart coveragePart = multipart.getBodyPart(1); assertEquals("image/tiff", coveragePart.getContentType()); assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]); // make sure we can read the coverage back ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next(); reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream())); RenderedImage image = reader.read(0); // check the image is suitably small (without requiring an exact size) assertTrue(image.getWidth() < 1000); assertTrue(image.getHeight() < 1000); }
From source file:org.geoserver.wcs.GetCoverageTest.java
@Test public void testRasterFilterGreen() throws Exception { String queryString = "wcs?identifier=" + getLayerId(MOSAIC) + "&request=getcoverage" + "&service=wcs&version=1.1.1&&format=image/tiff" + "&BoundingBox=0,0,1,1,urn:ogc:def:crs:EPSG:6.6:4326" + "&CQL_FILTER=location like 'green%25'"; MockHttpServletResponse response = getAsServletResponse(queryString); // parse the multipart, check there are two parts Multipart multipart = getMultipart(response); assertEquals(2, multipart.getCount()); BodyPart coveragePart = multipart.getBodyPart(1); assertEquals("image/tiff", coveragePart.getContentType()); assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]); // make sure we can read the coverage back ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next(); reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream())); RenderedImage image = reader.read(0); // check the pixel int[] pixel = new int[3]; image.getData().getPixel(0, 0, pixel); assertEquals(0, pixel[0]);/*from w w w .j ava 2s. co m*/ assertEquals(255, pixel[1]); assertEquals(0, pixel[2]); }
From source file:org.geoserver.wcs.GetCoverageTest.java
@Test public void testRasterFilterRed() throws Exception { String queryString = "wcs?identifier=" + getLayerId(MOSAIC) + "&request=getcoverage" + "&service=wcs&version=1.1.1&&format=image/tiff" + "&BoundingBox=0,0,1,1,urn:ogc:def:crs:EPSG:6.6:4326" + "&CQL_FILTER=location like 'red%25'"; MockHttpServletResponse response = getAsServletResponse(queryString); // parse the multipart, check there are two parts Multipart multipart = getMultipart(response); assertEquals(2, multipart.getCount()); BodyPart coveragePart = multipart.getBodyPart(1); assertEquals("image/tiff", coveragePart.getContentType()); assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]); // make sure we can read the coverage back ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next(); reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream())); RenderedImage image = reader.read(0); // check the pixel int[] pixel = new int[3]; image.getData().getPixel(0, 0, pixel); assertEquals(255, pixel[0]);// w ww . j av a 2 s.c o m assertEquals(0, pixel[1]); assertEquals(0, pixel[2]); }
From source file:org.geoserver.wcs.GetCoverageTest.java
@Test public void testReadNoGridCRS() throws Exception { String request = // " <wcs:GetCoverage service=\"WCS\" version=\"1.1.1\" " + " xmlns:wcs=\"http://www.opengis.net/wcs/1.1.1\" " + " xmlns:gml=\"http://www.opengis.net/gml\"" + " xmlns:ows=\"http://www.opengis.net/ows/1.1\" >\n" + " <ows:Identifier>" + getLayerId(MockData.TASMANIA_DEM) + " </ows:Identifier>\n" + " <wcs:DomainSubset>\n" + " <ows:BoundingBox crs=\"http://www.opengis.net/gml/srs/epsg.xml#4326\">\n" + " <ows:LowerCorner>-180.0 -90.0</ows:LowerCorner>\n" + " <ows:UpperCorner>180.0 90.0</ows:UpperCorner>\n" + " </ows:BoundingBox>\n" // + " </wcs:DomainSubset>\n" + " <wcs:Output format=\"image/tiff\"/>\n" + " </wcs:GetCoverage>"; MockHttpServletResponse response = postAsServletResponse("wcs", request); // parse the multipart, check there are two parts Multipart multipart = getMultipart(response); assertEquals(2, multipart.getCount()); BodyPart coveragePart = multipart.getBodyPart(1); assertEquals("image/tiff", coveragePart.getContentType()); assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]); // make sure we can read the coverage back ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next(); reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream())); RenderedImage image = reader.read(0); }
From source file:org.geoserver.wcs.GetCoverageTest.java
/** * This tests just ended up throwing an exception as the coverage being encoded * was too large due to a bug in the scales estimation * /*from w w w. j a v a 2 s. com*/ * @throws Exception */ @Test public void testRotatedPost() throws Exception { String request = "<GetCoverage xmlns=\"http://www.opengis.net/wcs/1.1.1\" xmlns:gml=\"http://www.opengis.net/gml\"\n" + " xmlns:ows11=\"http://www.opengis.net/ows/1.1\"\n" + " xmlns:ows=\"http://www.opengis.net/ows/1.1\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \r\n" + // " xmlns:wcs=\"http://schemas.opengis.net/wcs/1.1.1\"\n" + " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n" + " service=\"WCS\"\n" + " version=\"1.1.1\"\n" + " xsi:schemaLocation=\"http://www.opengis.net/wcs/1.1.1 http://schemas.opengis.net/wcs/1.1.1/wcsAll.xsd\">\n" + " <ows11:Identifier>RotatedCad</ows11:Identifier>\n" + " <DomainSubset>\n" + " <ows11:BoundingBox crs=\"urn:ogc:def:crs:OGC:1.3:CRS84\">\n" + " <ows11:LowerCorner>7.7634301664746515 45.14713380418506</ows11:LowerCorner>\n" + " <ows11:UpperCorner>7.764350661575157 45.14763319238466</ows11:UpperCorner>\n" + " </ows11:BoundingBox>\n" + " </DomainSubset>\n" + " <Output format=\"image/tiff\"/>\n" + "</GetCoverage>"; MockHttpServletResponse response = postAsServletResponse("wcs", request); // parse the multipart, check there are two parts Multipart multipart = getMultipart(response); assertEquals(2, multipart.getCount()); BodyPart coveragePart = multipart.getBodyPart(1); assertEquals("image/tiff", coveragePart.getContentType()); assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]); // make sure we can read the coverage back ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next(); reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream())); RenderedImage image = reader.read(0); // check the image is suitably small (without requiring an exact size) assertTrue(image.getWidth() < 1000); assertTrue(image.getHeight() < 1000); }
From source file:com.gargoylesoftware.htmlunit.javascript.host.canvas.CanvasRenderingContext2D.java
/** * Draws images onto the canvas./*from w ww . j a va 2s. c om*/ * * @param image an element to draw into the context * @param sx the X coordinate of the top left corner of the sub-rectangle of the source image * to draw into the destination context * @param sy the Y coordinate of the top left corner of the sub-rectangle of the source image * to draw into the destination context * @param sWidth the width of the sub-rectangle of the source image to draw into the destination context * @param sHeight the height of the sub-rectangle of the source image to draw into the destination context * @param dx the X coordinate in the destination canvas at which to place the top-left corner of the source image * @param dy the Y coordinate in the destination canvas at which to place the top-left corner of the source image * @param dWidth the width to draw the image in the destination canvas. This allows scaling of the drawn image * @param dHeight the height to draw the image in the destination canvas. This allows scaling of the drawn image */ @JsxFunction @SuppressWarnings("unused") public void drawImage(final Object image, final int sx, final int sy, final Object sWidth, final Object sHeight, final Object dx, final Object dy, final Object dWidth, final Object dHeight) { Integer dxI; Integer dyI; Integer dWidthI = null; Integer dHeightI = null; Integer sWidthI = null; Integer sHeightI = null; if (dx != Undefined.instance) { dxI = ((Number) dx).intValue(); dyI = ((Number) dy).intValue(); dWidthI = ((Number) dWidth).intValue(); dHeightI = ((Number) dHeight).intValue(); } else { dxI = sx; dyI = sy; } if (sWidth != Undefined.instance) { sWidthI = ((Number) sWidth).intValue(); sHeightI = ((Number) sHeight).intValue(); } try { if (image instanceof HTMLImageElement) { final ImageReader imageReader = ((HtmlImage) ((HTMLImageElement) image).getDomNodeOrDie()) .getImageReader(); if (imageReader.getNumImages(true) != 0) { final BufferedImage img = imageReader.read(0); graphics2D_.drawImage(img, dxI, dyI, null); } } } catch (final IOException ioe) { throw Context.throwAsScriptRuntimeEx(ioe); } }
From source file:org.n52.v3d.terrainserver.profileservice.ProfileServlet.java
/** * bearbeitet HTTP-Get-Anfragen an das Servlet.<p> * @param pRequest HTTP-Anfrage-Objekt//from www .jav a 2 s. c o m * @param pResponse HTTP-Antwort-Objekt * @throws ServletException * @throws IOException */ public void doGet(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException { T3dTimeList lTimeProt = new T3dTimeList(); // zur Protokollierung der Rechenzeiten lTimeProt.addTimeStamp("init"); // Eindeutigen Temporrdatei-Rumpf fr aktuelle Anfrage festlegen: String lTmpName = "~" + (mCounter++) + "_" + new java.util.Date().getTime(); try { // Request-Parameter holen: HttpRequestParams lReqParams = this.fetchRequestParameters(pRequest); String lRequest = (String) lReqParams.getParameterValue("REQUEST"); VgLineString lDefLine = (VgLineString) lReqParams.getParameterValue("DEFLINE"); String lSRS = (String) lReqParams.getParameterValue("SRS"); String lFormat = (String) lReqParams.getParameterValue("FORMAT"); int lWidth = ((Integer) lReqParams.getParameterValue("WIDTH")).intValue(); int lHeight = ((Integer) lReqParams.getParameterValue("HEIGHT")).intValue(); double lExaggeration = ((Double) lReqParams.getParameterValue("EXAGGERATION")).doubleValue(); // todo sinnvoll? //int lVisAdds = ((Integer) lReqParams.getParameterValue("VISADDS")).intValue(); VgPoint lPoint = (VgPoint) lReqParams.getParameterValue("POINT"); if (lRequest.equalsIgnoreCase("GetCapabilities")) { HttpStandardResponse response = new HttpStandardResponse(); response.sendXMLFile(mCapabilitiesFile, pResponse); // todo: serverrun/Capabilities.xml einrichten und web.xml-Additions this.logGetCapabilitiesInfo(lTmpName, pRequest); return; } if (!(lRequest.equalsIgnoreCase("GetGraph") || lRequest.equalsIgnoreCase("GetElevation"))) throw new T3dException("Illegal request type " + lRequest + "..."); // Request-Parameter aufbereiten und Wertebereiche prfen: ParameterPreparer pp = new ParameterPreparer(); lSRS = pp.prepareSRS(lSRS); lFormat = pp.prepareFORMAT(lFormat, lRequest); if (lRequest.equalsIgnoreCase("GetGraph")) { lWidth = pp.prepareWIDTH(lWidth); lHeight = pp.prepareHEIGHT(lHeight); } if (lRequest.equalsIgnoreCase("GetElevation")) { String str = "" + lPoint.getX() + "," + lPoint.getY() + ",0.0," /* erster Eckpunkt = Interpolationspunkt */ + lPoint.getX() + "," + lPoint.getY() + ",0.0"; /* zweiter Eckpunkt als Hilfspunkt */ lDefLine = new GmLineString(str); if (lPoint instanceof VgPoint) { lPoint.setSRS(lSRS); } } sLogger.debug("ProfileServlet (" + lTmpName + "): Received " + lRequest + " request."); lTimeProt.setFinished("init"); // Hhenmodell berechnen (Gridding): lTimeProt.addTimeStamp("dem_access"); final boolean lDebug = false; // todo: auf 'false' setzen if (lDebug) System.out.println("lDefLine = " + lDefLine); VgEnvelope lBBox = lDefLine.envelope(); lBBox.setSRS(lSRS); lBBox = this.assureBBoxExtent(lBBox); if (lDebug) System.out.println("lBBox = " + lBBox); GmSimpleElevationGrid lTerrain = this.setUpTerrain(lBBox); if (lDebug) { System.out.println("lTerrain = " + lTerrain); System.out.println("lTerrain.envelope = " + lTerrain.getGeometry().envelope()); } lTimeProt.setFinished("dem_access"); // Profil generieren: lTimeProt.addTimeStamp("profile_generation"); FltElevationGrid2Profile lProc = new FltElevationGrid2Profile(); VgProfile lProfile = lProc.transform(lTerrain, lDefLine); lTimeProt.setFinished("profile_generation"); if (lRequest.equalsIgnoreCase("GetGraph")) { // Ergebnisbild generieren: lTimeProt.addTimeStamp("rendering"); IoProfileWriter lWriter = new IoProfileWriter("SVG"); // stets SVG generieren String lResFile = mWorkingDirectory + "/" + lTmpName + ".svg"; lWriter.writeToFile(lProfile, lResFile); boolean lSendAsPngImage = false; String lResFilePng = ""; if (lFormat.equalsIgnoreCase("image/png")) lSendAsPngImage = true; if (lSendAsPngImage) { PNGTranscoder lTranscoder = new PNGTranscoder(); String lSvgURI = new File(lResFile).toURL().toString(); TranscoderInput lInput = new TranscoderInput(lSvgURI); lResFilePng = mWorkingDirectory + "/" + lTmpName + ".png"; OutputStream lOStream = new FileOutputStream(lResFilePng); TranscoderOutput lOutput = new TranscoderOutput(lOStream); lTranscoder.transcode(lInput, lOutput); lOStream.flush(); lOStream.close(); } lTimeProt.setFinished("rendering"); // Ergebnisbild als Antwort senden: lTimeProt.addTimeStamp("send_response"); if (!lSendAsPngImage) { pResponse.setContentType("image/svg+xml"); // MIME-Typ fr Antwort setzen BufferedReader lDatRead; try { lDatRead = new BufferedReader(new FileReader(lResFile)); } catch (FileNotFoundException e) { throw new T3dException("Internal error while reading \"" + lResFile + "\"."); } PrintWriter out = pResponse.getWriter(); // PrintWriter auf die Antwort aufsetzen String line = lDatRead.readLine(); while (line != null) { // generierte Temporrdatei zeilenweise senden out.println(line); line = lDatRead.readLine(); } lDatRead.close(); out.flush(); out.close(); } else { // Bild senden (vgl. Code aus WebTerrainServlet: try { File f = new File(lResFilePng); ImageInputStream is = ImageIO.createImageInputStream(f); Iterator iter = ImageIO.getImageReaders(is); // liefert PNG-ImageReader ImageReader reader = (ImageReader) iter.next(); reader.setInput(is, true); // seek forward only? BufferedImage lImage = reader.read(0); OutputStream out = pResponse.getOutputStream(); ImageIO.setUseCache(false); // wichtig! pResponse.setContentType(lFormat); // MIME-Typ fr Antwort setzen String resExt = MimeTypeHelper.getFileExtension(lFormat); try { ImageIO.write(lImage, resExt, out); // resExt ist informaler Formatname... } catch (Exception e) { throw new T3dException("Did not finish PNG image send process. " + e.getMessage(), 103); // todo fehler-nr. prfen und in doku } is.close(); out.close(); } catch (IOException e) { throw new T3dException( "An I/O exception occured. The servlet could not send an image reponse.", 106); // todo fehler-nr. prfen und in doku } } File fSvg = new File(lResFile); fSvg.delete(); if (lSendAsPngImage) { File fPng = new File(lResFilePng); fPng.delete(); } lTimeProt.setFinished("send_response"); } else { if (lRequest.equalsIgnoreCase("GetElevation")) { lTimeProt.addTimeStamp("send_response"); double x, y, z; try { x = ((VgLineString) (lProfile.getGeometry())).getVertex(0).getX(); // = lPoint.getX() y = ((VgLineString) (lProfile.getGeometry())).getVertex(0).getY(); // = lPoint.getY() z = (lProfile.getTZPair(0))[1]; } catch (Throwable e) { throw new T3dException("No elevation information available."); } // Antwort senden: short lCase = 0; if (lFormat.equalsIgnoreCase("text/plain")) lCase = 1; if (lFormat.equalsIgnoreCase("text/xml")) lCase = 2; if (lFormat.equalsIgnoreCase("text/html")) lCase = 3; if (lFormat.equalsIgnoreCase("text/comma-separated-values")) lCase = 4; if (lCase <= 0) throw new T3dException("Internal servlet error."); // Kann nicht auftreten pResponse.setContentType(lFormat); // MIME-Typ fr Antwort setzen PrintWriter out = pResponse.getWriter(); // PrintWriter auf die Antwort aufsetzen switch (lCase) { case 1: out.println("Position:"); out.println("SRS: " + lPoint.getSRS()); // = lSRS out.println("X = " + x); out.println("Y = " + y); out.println(""); out.println("Elevation = " + z); break; case 2: out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\" ?>"); out.println("<ServiceResponse>"); out.println(" <Position>"); out.println(" <SRS>" + lPoint.getSRS() + "</SRS>"); // = lSRS out.println(" <X>" + x + "</X>"); out.println(" <Y>" + y + "</Y>"); out.println(" </Position>"); out.println(" <Elevation>" + z + "</Elevation>"); out.println("</ServiceResponse>"); break; case 3: out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); out.println("<html>"); out.println("<head>"); out.println("<title>52N terrainServer elevation information</title>"); out.println("<font face=\"Verdana, Arial, Helvetica\" size=1>"); out.println("<meta http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">"); out.println("<body text=#000000 bgColor=#ffffff leftMargin=0 topMargin=0>"); out.println("<table border=\"1\">"); out.println("<tr><td><b>Position:</b></td><td><br></td></tr>"); out.println("<tr><td>SRS:</td><td>" + lPoint.getSRS() + "</td></tr>"); // lPoint.getSRS() = lSRS out.println("<tr><td>X:</td><td>" + x + "<td></tr>"); out.println("<tr><td>Y:</td><td>" + y + "<td></tr>"); out.println("<tr><td><b>Elevation:</b></td><td>" + z + "<td></tr>"); out.println("</table>"); out.println("</html>"); break; case 4: out.println(z); break; } out.flush(); out.close(); lTimeProt.setFinished("send_response"); } } //String lOutputFormatInfo = lFormat + " (" + lWidth + "x" + lHeight + ")"; if (lRequest.equalsIgnoreCase("GetGraph")) this.logGetGraphInfo(lTmpName, lTerrain, lDefLine, lTimeProt, pRequest, lFormat /*lOutputFormatInfo*/); else { if (lRequest.equalsIgnoreCase("GetElevation")) this.logGetElevationInfo(lTmpName, lTerrain, lPoint, lTimeProt, pRequest, lFormat); } sLogger.debug("ProfileServlet (" + lTmpName + "): Duly finished execution."); } catch (Throwable e) { sLogger.debug("ProfileServlet (" + lTmpName + "): Aborting execution. Error: " + e.getMessage()); HttpStandardResponse response = new HttpStandardResponse(); try { response.sendException(e.getMessage(), pResponse); } catch (Throwable e2) { try { response.sendException(e.getMessage(), pResponse); } catch (Throwable e3) { System.out.println("ProfileServlet: FATAL ERROR - " + e3.getMessage()); } } try { this.logErrorInfo(lTmpName, lTimeProt, pRequest, e); } catch (Throwable e2) { System.out.println("ProfileServlet: FATAL ERROR - " + e2.getMessage()); } } }