List of usage examples for javax.imageio.stream ImageInputStream close
void close() throws IOException;
From source file:de.cismet.cids.custom.objecteditors.wunda_blau.WebDavPicturePanel.java
/** * DOCUMENT ME!/* ww w .j av a 2 s . c om*/ * * @param fileName DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception DOCUMENT ME! */ private BufferedImage downloadImageFromWebDAV(final String fileName) throws Exception { final InputStream iStream = webdavHelper.getFileFromWebDAV(fileName, webdavDirectory, getConnectionContext()); try { final ImageInputStream iiStream = ImageIO.createImageInputStream(iStream); final Iterator<ImageReader> itReader = ImageIO.getImageReaders(iiStream); if (itReader.hasNext()) { final ImageReader reader = itReader.next(); final ProgressMonitor monitor = new ProgressMonitor(this, "Bild wird bertragen...", "", 0, 100); // monitor.setMillisToPopup(500); reader.addIIOReadProgressListener(new IIOReadProgressListener() { @Override public void sequenceStarted(final ImageReader source, final int minIndex) { } @Override public void sequenceComplete(final ImageReader source) { } @Override public void imageStarted(final ImageReader source, final int imageIndex) { monitor.setProgress(monitor.getMinimum()); } @Override public void imageProgress(final ImageReader source, final float percentageDone) { if (monitor.isCanceled()) { try { iiStream.close(); } catch (final IOException ex) { // NOP } } else { monitor.setProgress(Math.round(percentageDone)); } } @Override public void imageComplete(final ImageReader source) { monitor.setProgress(monitor.getMaximum()); } @Override public void thumbnailStarted(final ImageReader source, final int imageIndex, final int thumbnailIndex) { } @Override public void thumbnailProgress(final ImageReader source, final float percentageDone) { } @Override public void thumbnailComplete(final ImageReader source) { } @Override public void readAborted(final ImageReader source) { monitor.close(); } }); final ImageReadParam param = reader.getDefaultReadParam(); reader.setInput(iiStream, true, true); final BufferedImage result; try { result = reader.read(0, param); } finally { reader.dispose(); iiStream.close(); } return result; } else { return null; } } finally { IOUtils.closeQuietly(iStream); } }
From source file:org.medici.bia.controller.manuscriptviewer.IIPImageServerController.java
/** * This method return image and tile information. * /*from w w w .j a v a 2s .co m*/ * EXAMPLE OUTPUT : IIP:1.0 Max-size:1832 2448 Tile-size:128 128 * Resolution-number:6 * * @param httpServletRequest * @param response * */ private void generateInformationsTiledImage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { File imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path") + httpServletRequest.getParameter("FIF")); ImageInputStream imageInputStream = null; Integer imageWidth = new Integer(0); Integer imageHeight = new Integer(0); Integer tileWidth = new Integer(0); Integer tileHeight = new Integer(0); Integer resolutionNumber = new Integer(0); try { if (imageFile.canRead()) { // Reading complete tiff information imageInputStream = ImageIO.createImageInputStream(imageFile); } else { logger.error("File " + imageFile.toString() + " is not present on filesystem. "); imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path") + ApplicationPropertyManager.getApplicationProperty("iipimage.image.notavailable")); if (imageFile.canRead()) { // Reading complete tiff information imageInputStream = ImageIO.createImageInputStream(imageFile); } else { logger.error("File " + imageFile.toString() + " is not present on filesystem. "); } } if (imageInputStream != null) { Iterator<ImageReader> readers = ImageIO.getImageReaders(imageInputStream); if (readers.hasNext()) { ImageReader reader = readers.next(); reader.setInput(imageInputStream, false, true); tileWidth = reader.getTileWidth(0); tileHeight = reader.getTileHeight(0); imageWidth = reader.getWidth(0); imageHeight = reader.getHeight(0); // Last level is not readable, I don't know why but i remove // this resolutionNumber = reader.getNumImages(true); } } } catch (IOException ioException) { logger.debug(ioException); } finally { try { if (imageInputStream != null) { imageInputStream.close(); } } catch (IOException ioException) { } try { httpServletResponse.setContentType("text/plain"); ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream(); servletOutputStream.println("IIP:1.0"); servletOutputStream.println("Max-size:" + imageWidth + " " + imageHeight); servletOutputStream.println("Tile-size:" + tileWidth + " " + tileHeight); servletOutputStream.println("Resolution-number:" + resolutionNumber); servletOutputStream.println(""); httpServletResponse.getOutputStream().flush(); } catch (IOException ioException) { logger.error(ioException); } } }
From source file:org.apache.pdfbox.pdmodel.graphics.image.SampledImageReader.java
private static BufferedImage fromAny(PDImage pdImage, WritableRaster raster, COSArray colorKey) throws IOException { final PDColorSpace colorSpace = pdImage.getColorSpace(); final int numComponents = colorSpace.getNumberOfComponents(); final int width = pdImage.getWidth(); final int height = pdImage.getHeight(); final int bitsPerComponent = pdImage.getBitsPerComponent(); final float[] decode = getDecodeArray(pdImage); // read bit stream ImageInputStream iis = null; try {//ww w . j av a2 s . c o m // create stream iis = new MemoryCacheImageInputStream(pdImage.createInputStream()); final float sampleMax = (float) Math.pow(2, bitsPerComponent) - 1f; final boolean isIndexed = colorSpace instanceof PDIndexed; // init color key mask float[] colorKeyRanges = null; BufferedImage colorKeyMask = null; if (colorKey != null) { colorKeyRanges = colorKey.toFloatArray(); colorKeyMask = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); } // calculate row padding int padding = 0; if (width * numComponents * bitsPerComponent % 8 > 0) { padding = 8 - (width * numComponents * bitsPerComponent % 8); } // read stream byte[] srcColorValues = new byte[numComponents]; byte[] alpha = new byte[1]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { boolean isMasked = true; for (int c = 0; c < numComponents; c++) { int value = (int) iis.readBits(bitsPerComponent); // color key mask requires values before they are decoded if (colorKeyRanges != null) { isMasked &= value >= colorKeyRanges[c * 2] && value <= colorKeyRanges[c * 2 + 1]; } // decode array final float dMin = decode[c * 2]; final float dMax = decode[(c * 2) + 1]; // interpolate to domain float output = dMin + (value * ((dMax - dMin) / sampleMax)); if (isIndexed) { // indexed color spaces get the raw value, because the TYPE_BYTE // below cannot be reversed by the color space without it having // knowledge of the number of bits per component srcColorValues[c] = (byte) Math.round(output); } else { // interpolate to TYPE_BYTE int outputByte = Math .round(((output - Math.min(dMin, dMax)) / Math.abs(dMax - dMin)) * 255f); srcColorValues[c] = (byte) outputByte; } } raster.setDataElements(x, y, srcColorValues); // set alpha channel in color key mask, if any if (colorKeyMask != null) { alpha[0] = (byte) (isMasked ? 255 : 0); colorKeyMask.getRaster().setDataElements(x, y, alpha); } } // rows are padded to the nearest byte iis.readBits(padding); } // use the color space to convert the image to RGB BufferedImage rgbImage = colorSpace.toRGBImage(raster); // apply color mask, if any if (colorKeyMask != null) { return applyColorKeyMask(rgbImage, colorKeyMask); } else { return rgbImage; } } finally { if (iis != null) { iis.close(); } } }
From source file:org.apache.pdfbox.pdmodel.graphics.shading.Type4ShadingContext.java
private List<ShadedTriangle> collectTriangles(PDShadingType4 freeTriangleShadingType, AffineTransform xform, Matrix matrix) throws IOException { COSDictionary dict = freeTriangleShadingType.getCOSObject(); PDRange rangeX = freeTriangleShadingType.getDecodeForParameter(0); PDRange rangeY = freeTriangleShadingType.getDecodeForParameter(1); PDRange[] colRange = new PDRange[numberOfColorComponents]; for (int i = 0; i < numberOfColorComponents; ++i) { colRange[i] = freeTriangleShadingType.getDecodeForParameter(2 + i); }/* ww w. j a v a 2 s . com*/ List<ShadedTriangle> list = new ArrayList<ShadedTriangle>(); long maxSrcCoord = (long) Math.pow(2, bitsPerCoordinate) - 1; long maxSrcColor = (long) Math.pow(2, bitsPerColorComponent) - 1; COSStream stream = (COSStream) dict; ImageInputStream mciis = new MemoryCacheImageInputStream(stream.createInputStream()); try { byte flag = (byte) 0; try { flag = (byte) (mciis.readBits(bitsPerFlag) & 3); } catch (EOFException ex) { LOG.error(ex); } while (true) { Vertex p0, p1, p2; Point2D[] ps; float[][] cs; int lastIndex; try { switch (flag) { case 0: p0 = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix, xform); flag = (byte) (mciis.readBits(bitsPerFlag) & 3); if (flag != 0) { LOG.error("bad triangle: " + flag); } p1 = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix, xform); mciis.readBits(bitsPerFlag); if (flag != 0) { LOG.error("bad triangle: " + flag); } p2 = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix, xform); ps = new Point2D[] { p0.point, p1.point, p2.point }; cs = new float[][] { p0.color, p1.color, p2.color }; list.add(new ShadedTriangle(ps, cs)); flag = (byte) (mciis.readBits(bitsPerFlag) & 3); break; case 1: case 2: lastIndex = list.size() - 1; if (lastIndex < 0) { LOG.error("broken data stream: " + list.size()); } else { ShadedTriangle preTri = list.get(lastIndex); p2 = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix, xform); ps = new Point2D[] { flag == 1 ? preTri.corner[1] : preTri.corner[0], preTri.corner[2], p2.point }; cs = new float[][] { flag == 1 ? preTri.color[1] : preTri.color[0], preTri.color[2], p2.color }; list.add(new ShadedTriangle(ps, cs)); flag = (byte) (mciis.readBits(bitsPerFlag) & 3); } break; default: LOG.warn("bad flag: " + flag); break; } } catch (EOFException ex) { break; } } } finally { mciis.close(); } return list; }
From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ImageUtils.java
/** * Converts image raster data to a JPEG with RGB color space. Only images with color space CMYK and YCCK are * converted, other images are left untouched. * * Rationale: Java's ImageIO can't process 4-component images and Java2D can't apply AffineTransformOp either, * so we have to convert raster data to a JPG with RGB color space. * * The technique used in this method is due to Mark Stephens, and free for any use. See * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4799903 or * http://www.mail-archive.com/java2d-interest@capra.eng.sun.com/msg03247.html * * @param is the image data/* w w w. j av a2 s. c o m*/ * @param colorModel the color model of the image * @return the RGB version of the supplied image */ public static InputStream convertToRGB(InputStream is, ColorModel colorModel) throws IOException, UnsupportedImageException { if (colorModel != ColorModel.CMYK && colorModel != ColorModel.YCCK) { return is; } // Get an ImageReader. ImageInputStream input = ImageIO.createImageInputStream(is); try { Iterator<ImageReader> readers = ImageIO.getImageReaders(input); if (readers == null || !readers.hasNext()) { throw new UnsupportedImageException("No ImageReaders found"); } ImageReader reader = readers.next(); reader.setInput(input); Raster raster = reader.readRaster(0, reader.getDefaultReadParam()); int w = raster.getWidth(); int h = raster.getHeight(); byte[] rgb = new byte[w * h * 3]; switch (colorModel) { case YCCK: { float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null); float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null); float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null); float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null); for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) { float k = 220 - K[i], y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i]; double val = y + 1.402 * (cr - 128) - k; val = (val - 128) * .65f + 128; rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k; val = (val - 128) * .65f + 128; rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); val = y + 1.772 * (cb - 128) - k; val = (val - 128) * .65f + 128; rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); } break; } case CMYK: { int[] C = raster.getSamples(0, 0, w, h, 0, (int[]) null); int[] M = raster.getSamples(0, 0, w, h, 1, (int[]) null); int[] Y = raster.getSamples(0, 0, w, h, 2, (int[]) null); int[] K = raster.getSamples(0, 0, w, h, 3, (int[]) null); for (int i = 0, imax = C.length, base = 0; i < imax; i++, base += 3) { int c = 255 - C[i]; int m = 255 - M[i]; int y = 255 - Y[i]; int k = 255 - K[i]; float kk = k / 255f; rgb[base] = (byte) (255 - Math.min(255f, c * kk + k)); rgb[base + 1] = (byte) (255 - Math.min(255f, m * kk + k)); rgb[base + 2] = (byte) (255 - Math.min(255f, y * kk + k)); } break; } } // from other image types we know InterleavedRaster's can be // manipulated by AffineTransformOp, so create one of those. raster = Raster.createInterleavedRaster(new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3, new int[] { 0, 1, 2 }, null); ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); java.awt.image.ColorModel cm = new ComponentColorModel(cs, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); BufferedImage convertedImage = new BufferedImage(cm, (WritableRaster) raster, true, null); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(convertedImage, "jpg", os); return new ByteArrayInputStream(os.toByteArray()); } finally { IOUtils.closeQuietly(is); if (input != null) { input.close(); } } }
From source file:org.n52.v3d.terrainserver.povraywts.WebTerrainServlet.java
/** * bearbeitet HTTP-Get-Anfragen an das Servlet.<p> * @param pRequest HTTP-Anfrage-Objekt/*from w w w. java2s. 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"); /* Enumeration hnames = pRequest.getHeaderNames(); while(hnames.hasMoreElements()){ String header = (String) hnames.nextElement(); Enumeration headers = pRequest.getHeaders(header); while (headers.hasMoreElements()) { System.out.println("header: " + header + ", value=" + (String) headers.nextElement()); //if (header.equalsIgnoreCase("accept") && pRequest.getHeader(header).startsWith("image/")) // return; } } */ // Eindeutigen Temporrdatei-Rumpf fr aktuelle Anfrage festlegen: String lTmpName = "~" + (mCounter++) + "_" + new java.util.Date().getTime(); // Objektdefinitionen fr Temporrdateien-Verwaltung: boolean lCacheScene = false; TempFileHandler lRequTmpMngr = null; boolean lKeepTempFilesInCaseOfError = false; TempFileHandler lSessionTmpMngr = null; try { // Request-Parameter holen: HttpRequestParams lReqParams = this.fetchRequestParameters(pRequest); String lSRS = (String) lReqParams.getParameterValue("SRS"); String lRequest = (String) lReqParams.getParameterValue("REQUEST"); GmEnvelope lBBox = (GmEnvelope) lReqParams.getParameterValue("BBOX"); VgPoint lPoi; try { lPoi = (VgPoint) lReqParams.getParameterValue("POI"); } catch (T3dException e) { lPoi = null; } double lYaw = ((Double) lReqParams.getParameterValue("YAW")).doubleValue(); double lPitch = ((Double) lReqParams.getParameterValue("PITCH")).doubleValue(); double lDistance; try { lDistance = ((Double) lReqParams.getParameterValue("DISTANCE")).doubleValue(); } catch (T3dException e) { lDistance = 0.; } double lAov = ((Double) lReqParams.getParameterValue("AOV")).doubleValue(); 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(); String lDrape = (String) lReqParams.getParameterValue("DRAPE"); String lWmsLayers = (String) lReqParams.getParameterValue("WMSLAYERS"); double lWmsRes = ((Double) lReqParams.getParameterValue("WMSRES")).doubleValue(); double lSearchRadius = ((Double) lReqParams.getParameterValue("SEARCHRADIUS")).doubleValue(); int lVisAdds = ((Integer) lReqParams.getParameterValue("VISADDS")).intValue(); boolean lTransparent = ((Boolean) lReqParams.getParameterValue("TRANSPARENT")).booleanValue(); String lBgColorHex = (String) lReqParams.getParameterValue("BGCOLOR"); lCacheScene = ((Boolean) lReqParams.getParameterValue("CACHESCENE")).booleanValue(); String lExceptions = (String) lReqParams.getParameterValue("EXCEPTIONS"); int lQuality = ((Integer) lReqParams.getParameterValue("QUALITY")).intValue(); double lLightInt = ((Double) lReqParams.getParameterValue("LIGHTINT")).doubleValue(); String lMonProtUser = (String) lReqParams.getParameterValue("MONPROTUSER"); String lMonProtPasswd = (String) lReqParams.getParameterValue("MONPROTPASSWD"); if (lRequest.equalsIgnoreCase("GetCapabilities")) { HttpStandardResponse response = new HttpStandardResponse(); response.sendXMLFile(mCapabilitiesFile, pResponse); this.logGetCapabilitiesInfo(lTmpName, pRequest); return; } if (lRequest.equalsIgnoreCase("GetMonProtocol")) { // hier evtl. besseren Zugriffsschutz realisieren... if (pRequest.getMethod().equalsIgnoreCase("POST")) { if ((mMonProtUser != null && mMonProtPasswd != null && lMonProtUser.compareTo(mMonProtUser) == 0 && lMonProtPasswd.compareTo(mMonProtPasswd) == 0) || lMonProtUser.compareTo("wtsadmin") == 0 && lMonProtPasswd.compareTo("geheim") == 0) { this.monitorProtocol(pResponse); } } return; } if (!lRequest.equalsIgnoreCase("GetView")) { lKeepTempFilesInCaseOfError = false; throw new T3dException("Illegal request type " + lRequest + "..."); } // Request-Parameter aufbereiten und Wertebereiche prfen: ParameterPreparer pp = new ParameterPreparer(); lSRS = pp.prepareSRS(lSRS); lBBox = pp.prepareBBOX(lBBox, lSRS); lPoi = pp.preparePOI(lPoi, lSRS); lYaw = pp.prepareYAW(lYaw); lPitch = pp.preparePITCH(lPitch); lDistance = pp.prepareDISTANCE(lDistance); lAov = pp.prepareAOV(lAov); lWmsLayers = pp.prepareWMSLAYERS(lWmsLayers); lWmsRes = pp.prepareWMSRES(lWmsRes); lTransparent = pp.prepareTRANSPARENT(lTransparent); T3dColor lBgColor = pp.prepareBGCOLOR(lBgColorHex); lWidth = pp.prepareWIDTH(lWidth); lHeight = pp.prepareHEIGHT(lHeight); lExceptions = pp.prepareEXCEPTIONS(lExceptions); lQuality = pp.prepareQUALITY(lQuality); lLightInt = pp.prepareLIGHTINT(lLightInt); sLogger.debug("WebTerrainServlet (" + lTmpName + "): Received GetView request."); if (lSearchRadius < mSearchRadiusMin) // todo lSearchRadius = mSearchRadiusMin; if (!lBBox.hasMetricSRS()) { if (lBBox.hasGeographicSRS()) { // metrisch bentigte Parameter umrechnen lExaggeration /= Wgs84Helper.degree2meter; lSearchRadius /= Wgs84Helper.degree2meter; } else throw new T3dException("Missing SRS support for \"" + lBBox.getSRS() + "\"."); } // Temporrdateien-Verwaltung gewhrleisten und ggf. Session-Objekt holen: WTSSession lWtsSession = new WTSSession(); lWtsSession = this.setUpSession(lWtsSession, lCacheScene, pRequest, lBBox, lDrape, lWmsLayers); HttpSession lSession = lWtsSession.getHttpSession(); lRequTmpMngr = lWtsSession.getRequTempFileHandler(); if (lCacheScene) lSessionTmpMngr = lWtsSession.getSessionTempFileHandler(); lTimeProt.setFinished("init"); // Hhenmodell berechnen (Gridding): lTimeProt.addTimeStamp("dem_access"); VgElevationGrid lTerrain = this.setUpTerrain(lCacheScene, lSession, lBBox, lHeight, lWidth, lSearchRadius); lTimeProt.setFinished("dem_access"); // Drape holen: lTimeProt.addTimeStamp("drape_access"); String lDrapeFile = this.setUpDrape(lCacheScene, lWtsSession, lDrape, lWmsLayers, lBBox, lSRS, lWidth, lTerrain, lTmpName, lWmsRes); if (mLocalDebug) System.out.println("lDrapeFile = \"" + lDrapeFile + "\""); lTimeProt.setFinished("drape_access"); // POV-Ray-Szene definieren: lTimeProt.addTimeStamp("scene_def"); if (lDistance == 0. && lPoi == null) lDistance = this.determineDefaultDistance(lTerrain, lYaw * Math.PI / 180., lExaggeration, 2. * lAov); VsSimpleScene lScene = this.defineScene(lTerrain, lDrapeFile, lVisAdds, lDistance, lPoi, lYaw * Math.PI / 180., -lPitch * Math.PI / 180., lExaggeration, 2. * lAov); lScene.setBackgroundColor(lBgColor); lRequTmpMngr.addTempFile(mWorkingDirectory + "/" + lTmpName + ".pov"); lRequTmpMngr.addTempFile(mWorkingDirectory + "/" + lTmpName + ".bat"); lTimeProt.setFinished("scene_def"); // POV-Ray-Umgebung setzen und Szene rendern: // todo: alles noch zu POV-Ray-spezifisch -> Interface bauen/erweitern? / j3dwts-Servlet mit gemeinsamem Kern? lTimeProt.addTimeStamp("rendering"); this.configureRenderer(lScene, lWidth, lHeight, lTmpName, lLightInt); String lGifEncodedDEM = null; if (lCacheScene) // Dateinamen fr GIF-kodiertes Hhenmodell aus Session holen lGifEncodedDEM = (String) lSession.getAttribute("demgif_" + lSession.getId()); boolean lInstanceOverflow = false; try { if (mUseTimeSlices) { Long lTimeSlice = mTimeSliceAssigner.getAssignedSlice(); if (lTimeSlice != null) { long lTimeSliceStart = lTimeSlice.longValue(); long lCurrTime = mTimeSliceAssigner.currentTime(); if (lTimeSliceStart > lCurrTime) { long lDelay = lTimeSliceStart - lCurrTime; sLogger.debug("WebTerrainServlet (" + lTmpName + "): " + "Rendering process will be delayed for " + lDelay + " msecs..."); Thread.sleep(lDelay); } else { // Bem.: Fr lTimeSliceStart <= lCurrTime keine Verzgerung if (mLocalDebug) System.out.println("Rendering process will not be be delayed..."); } } else { // keine freie Zeitscheibe verfgbar lKeepTempFilesInCaseOfError = false; throw new T3dException("The server is too busy at the moment. Please try again later.", 100); } } if (mRendererInstances < mMaxRendererInstances) { mRendererInstances++; try { ((PovrayScene) lScene).setLocalDebug(mLocalDebug); if (lGifEncodedDEM == null) // CACHESCENE nicht gesetzt oder 1. Aufruf (GIF-Dateiname nicht in Session) ((PovrayScene) lScene).render(); else ((PovrayScene) lScene).renderCachedDEM(lGifEncodedDEM); } catch (Throwable e) { mRendererInstances--; lKeepTempFilesInCaseOfError = true; throw e; } //System.out.println("mRendererInstances = " + mRendererInstances); mRendererInstances--; } else lInstanceOverflow = true; } catch (T3dException e) { lKeepTempFilesInCaseOfError = true; throw e; } catch (Exception e) { lKeepTempFilesInCaseOfError = true; throw new T3dException("For unknown reasons, the scene could not be rendered...", 400); } if (lInstanceOverflow) { lKeepTempFilesInCaseOfError = false; throw new T3dException("The server is too busy at the moment. Please try again later.", 101); } if (lCacheScene) { // GIF in Session legen lSession.setAttribute("demgif_" + lSession.getId(), ((PovrayScene) lScene).getGifEncodedDEM()); lSessionTmpMngr.addTempFile(((PovrayScene) lScene).getGifEncodedDEM()); } else lRequTmpMngr.addTempFile(((PovrayScene) lScene).getGifEncodedDEM()); lRequTmpMngr.addTempFile(mWorkingDirectory + "/" + lTmpName + ".png"); if (!mRendererImmediateTermination) lTimeProt.setFinished("rendering"); // POV-Ray-Ergebnisbild holen: if (!mRendererImmediateTermination) lTimeProt.addTimeStamp("prepare_image"); String resExt = MimeTypeHelper.getFileExtension(((PovrayScene) lScene).getImageFormat()); String resFile = mWorkingDirectory + "/" + lTmpName + "." + resExt; sLogger.debug("WebTerrainServlet (" + lTmpName + "): Preparing image \"" + resFile + "\"..."); File f = new File(resFile); ImageInputStream is = ImageIO.createImageInputStream(f); if (!mRendererImmediateTermination) { if (is == null) { lKeepTempFilesInCaseOfError = true; throw new T3dException("For unknown reasons, the renderer did not generate an image file.", 401); } } else { int lMaxIntervalChecks = 40; long lCheckInterval = mRendererTimeout / lMaxIntervalChecks; int ct = 0; while (is == null && ct < lMaxIntervalChecks) { ct++; try { Thread.sleep(lCheckInterval); } catch (Exception e2) { } ; is = ImageIO.createImageInputStream(f); } if (is == null && ct >= lMaxIntervalChecks) { lKeepTempFilesInCaseOfError = true; throw new T3dException("An I/O exception occured. The renderer did not generate an image file.", 402); } lTimeProt.setFinished("rendering"); lTimeProt.addTimeStamp("prepare_image"); } BufferedImage lImage = this.prepareImage(is, lHeight, lWidth, lTerrain, lPitch, lYaw, lDistance, lExaggeration, (lVisAdds & 4) > 0, (lVisAdds & 8) > 0); lTimeProt.setFinished("prepare_image"); // Ergebnisbild als Antwort senden: lTimeProt.addTimeStamp("send_response"); try { this.sendResponse(lFormat, pResponse, lImage, resExt, lQuality); } catch (Throwable e) { is.close(); lKeepTempFilesInCaseOfError = false; throw e; } is.close(); lTimeProt.setFinished("send_response"); String lOutputFormatInfo = lFormat + " (" + lWidth + "x" + lHeight + ")"; this.logGetViewInfo(lTmpName, lTerrain, lTimeProt, pRequest, lOutputFormatInfo); //this.removeTempFiles(lRequTmpMngr, lSessionTmpMngr, lCacheScene); sLogger.debug("WebTerrainServlet (" + lTmpName + "): Duly finished execution."); } catch (Throwable e) { sLogger.debug("WebTerrainServlet (" + lTmpName + "): Aborting execution. Error: " + e.getMessage()); if (!lKeepTempFilesInCaseOfError) this.removeTempFiles(lRequTmpMngr, lSessionTmpMngr, lCacheScene); HttpStandardResponse response = new HttpStandardResponse(); try { String lExceptions = (String) this.fetchRequestParameters(pRequest).getParameterValue("EXCEPTIONS"); if (lExceptions.equalsIgnoreCase("application/vnd.ogc.se_inimage")) { int lWidth = ((Integer) this.fetchRequestParameters(pRequest).getParameterValue("WIDTH")) .intValue(); int lHeight = ((Integer) this.fetchRequestParameters(pRequest).getParameterValue("HEIGHT")) .intValue(); String lFormat = (String) this.fetchRequestParameters(pRequest).getParameterValue("FORMAT"); response.sendException(T3dExceptionMessage.getInstance().translate(e), pResponse, lFormat, lWidth, lHeight); } else response.sendException(e.getMessage(), pResponse); } catch (Throwable e2) { try { response.sendException(e.getMessage(), pResponse); } catch (Throwable e3) { System.out.println("WebTerrainServlet: FATAL ERROR - " + e2.getMessage()); } } try { this.logErrorInfo(lTmpName, lTimeProt, pRequest, e); } catch (Throwable e2) { System.out.println("WebTerrainServlet: FATAL ERROR - " + e2.getMessage()); } } }
From source file:org.medici.bia.controller.manuscriptviewer.IIPImageServerController.java
/** * This method retun a specific tiled image. * /*from www. ja v a 2 s. co m*/ * @param httpServletRequest * @param httpServletResponse */ private void generateFullImage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { File imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path") + httpServletRequest.getParameter("FIF")); ImageInputStream imageInputStream = null; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); InputStream inputStream = null; try { if (imageFile.canRead()) { // Reading complete tiff information imageInputStream = ImageIO.createImageInputStream(imageFile); } else { logger.error("File " + imageFile.toString() + " is not present on filesystem. "); imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path") + ApplicationPropertyManager.getApplicationProperty("iipimage.image.notavailable")); if (imageFile.canRead()) { // Reading complete tiff information imageInputStream = ImageIO.createImageInputStream(imageFile); } else { logger.error("File " + imageFile.toString() + " is not present on filesystem. "); } } if (imageInputStream != null) { Iterator<ImageReader> readers = ImageIO.getImageReaders(imageInputStream); ImageReader reader = readers.next(); reader.setInput(imageInputStream, true, true); // Reading image position requested Integer imageFullIndex = NumberUtils.createInteger(httpServletRequest.getParameter("full")); // Positioning at correct page BufferedImage pageImage = reader.read(imageFullIndex); // preparing image for output ImageIO.write(pageImage, "jpeg", byteArrayOutputStream); inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); // writing image to output httpServletResponse.setContentType("image/jpeg"); IOUtils.copy(inputStream, httpServletResponse.getOutputStream()); } // Flushing request httpServletResponse.getOutputStream().flush(); } catch (IOException ioException) { logger.debug(ioException); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException ioException) { } try { if (byteArrayOutputStream != null) { byteArrayOutputStream.close(); } } catch (IOException ioException) { } try { if (imageInputStream != null) { imageInputStream.close(); } } catch (IOException ioException) { } } }
From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java
private IIOImage createImage(InputStream istr, int attempt) throws ImageInterpreterException { ImageInputStream iis = null; Iterator<ImageReader> ri = null; ImageReadParam param = null;//w ww . j ava 2 s . co m ImageReader ir = null; BufferedImage bi = null; // Raster raster = null; // int[] bufferTypes = new int[] { DataBuffer.TYPE_BYTE, DataBuffer.TYPE_INT, DataBuffer.TYPE_FLOAT, DataBuffer.TYPE_DOUBLE, // DataBuffer.TYPE_SHORT, DataBuffer.TYPE_USHORT, DataBuffer.TYPE_UNDEFINED }; // Create raster from image reader try { iis = ImageIO.createImageInputStream(istr); ri = ImageIO.getImageReaders(iis); if (!ri.hasNext()) { // List<ImageReader> list = new ArrayList<ImageReader>(); // list.add(new JPEGImageReader(new JPEGImageReaderSpi())); ri = IteratorUtils.getIterator(new JPEGImageReader(new JPEGImageReaderSpi())); } } catch (IOException e) { throw new ImageInterpreterException("Error reading input stream: " + e.toString()); } while (ri.hasNext()) { ir = ri.next(); try { ir.setInput(iis); param = ir.getDefaultReadParam(); bi = ir.read(0, param); // raster = ir.readRaster(0, param); if (bi != null) { break; } } catch (Error e) { LOGGER.error("Failed to render image with ImageReader: " + e.toString()); continue; } catch (Exception e) { LOGGER.error("Failed to render image with ImageReader: " + e.toString()); continue; } } // store metadata IIOMetadata md = null; try { md = getImageMetadata(ir); } catch (ImageInterpreterException e) { LOGGER.error("Failed to extract metadata from image: " + e.getMessage()); InputStream patchedInputStream = null; if (attempt <= 1) { patchedInputStream = attempt == 0 ? new PatchInputStream(istr) : new RemoveHeaderInputStream(istr); if (istr != null) { try { istr.close(); } catch (IOException e1) { LOGGER.error("Failed to close input stream"); } } return createImage(patchedInputStream, attempt + 1); } else { LOGGER.error("Unable to read image metadata."); md = null; } } finally { if (iis != null) { try { iis.close(); } catch (IOException e) { LOGGER.error("Failed to close image stream", e); } } } // // create buffered image from raster // int count = 0; // while (count < bufferTypes.length) { // int bufferType = bufferTypes[count++]; // try { // SampleModel sm = RasterFactory.createPixelInterleavedSampleModel(bufferType, raster.getWidth(), raster.getHeight(), // raster.getNumBands()); // ColorModel cm = PlanarImage.createColorModel(sm); // // cm = bi.getColorModel(); // ColorSpace sourceColorSpace = cm.getColorSpace(); // ColorSpace destColorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB); // ColorConvertOp op = new ColorConvertOp(sourceColorSpace, destColorSpace, null); // // WritableRaster wraster = raster.createInterleavedRaster(bufferTypes[count-1], raster.getWidth(), raster.getHeight(), // raster.getNumBands(), null); // // WritableRaster wraster = op.createCompatibleDestRaster(raster); // WritableRaster wraster = op.filter(raster, null); // // Raster raster2 = bi.getRaster(); // // cm = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, bufferType); // // sm = bi.getSampleModel(); // // cm = bi.getColorModel(); // // cm = ColorModel.getRGBdefault(); // bi = new BufferedImage(cm, wraster, false, null); // cm.finalize(); // } catch (Error e) { // LOGGER.debug("Failed to render image with BufferType " + bufferType); // continue; // } catch (Exception e) { // LOGGER.debug("Failed to render image with BufferType " + bufferType); // continue; // } // break; // } if (bi == null) { throw new ImageInterpreterException("Failed to extract buffered image from image reader"); } IIOImage image = new IIOImage(bi, null, md); return image; }
From source file:org.medici.bia.controller.manuscriptviewer.IIPImageServerController.java
/** * // ww w.ja v a 2s.c o m * @param fileName * @param pageImage * @param tileNumber * @param xCoordinate * @param yCoordinate * @param httpServletResponse */ @SuppressWarnings("unused") private void generateTiledImage(String fileName, Integer pageImage, Integer tileNumber, Integer xCoordinate, Integer yCoordinate, HttpServletResponse httpServletResponse) { File imageFile = new File( ApplicationPropertyManager.getApplicationProperty("iipimage.image.path") + fileName); Integer imageWidth = new Integer(0); Integer imageHeight = new Integer(0); Integer tileWidth = new Integer(0); Integer tileHeight = new Integer(0); Integer resolutionNumber = new Integer(0); Integer convertedPageImage = new Integer(0); ImageInputStream imageInputStream = null; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); InputStream inputStream = null; try { if (imageFile.canRead()) { // Reading complete tiff information imageInputStream = ImageIO.createImageInputStream(imageFile); } else { logger.error("File " + imageFile.toString() + " is not present on filesystem. "); imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path") + ApplicationPropertyManager.getApplicationProperty("iipimage.image.notavailable")); if (imageFile.canRead()) { // Reading complete tiff information imageInputStream = ImageIO.createImageInputStream(imageFile); } else { logger.error("File " + imageFile.toString() + " is not present on filesystem. "); } } if (imageInputStream != null) { Iterator<ImageReader> readers = ImageIO.getImageReaders(imageInputStream); if (readers.hasNext()) { ImageReader reader = readers.next(); reader.setInput(imageInputStream, false, true); tileWidth = reader.getTileWidth(0); tileHeight = reader.getTileHeight(0); imageWidth = reader.getWidth(0); imageHeight = reader.getHeight(0); // Last level is not readable, I don't know why but i remove // this resolutionNumber = reader.getNumImages(true) - 1; // Calculate of image position, final -1 is beacause index // start from 0 and not from 1 convertedPageImage = resolutionNumber - pageImage; // We read our specific tile ImageReadParam param = reader.getDefaultReadParam(); param.setSourceRegion( new Rectangle(new Point(xCoordinate * tileWidth, yCoordinate * tileHeight), new Dimension(tileWidth, tileHeight))); BufferedImage subImage = reader.read(convertedPageImage, param); // preparing image for output ImageIO.write(subImage, "jpeg", byteArrayOutputStream); inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); // writing image to output httpServletResponse.setContentType("image/jpeg"); IOUtils.copy(inputStream, httpServletResponse.getOutputStream()); // Flushing request httpServletResponse.getOutputStream().flush(); } } else { logger.error("File " + imageFile.toString() + " is not present on filesystem."); } } catch (IOException ioException) { logger.error(ioException); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException ioException) { } try { if (byteArrayOutputStream != null) { byteArrayOutputStream.close(); } } catch (IOException ioException) { } try { if (imageInputStream != null) { imageInputStream.close(); } } catch (IOException ioException) { } } }
From source file:com.crimelab.service.GalleryServiceImpl.java
@Override public XWPFDocument create(GalleryResults galleryResults, HttpSession session) { XWPFDocument document = null;/*from w ww . j a v a2 s . c o m*/ //Insert into database galleryDAO.insertResults(galleryResults); try { //Retrieving Template InputStream inpDocx = session.getServletContext() .getResourceAsStream("/WEB-INF/templates/CompositeSketch.docx"); document = new XWPFDocument(inpDocx); //Adding the picture XWPFParagraph pictureHolder = document.createParagraph(); XWPFRun pictureRun = pictureHolder.createRun(); FileInputStream getPhoto = new FileInputStream(galleryResults.getPhotoLocation()); FileInputStream getImage = new FileInputStream(galleryResults.getPhotoLocation()); ImageInputStream imageInput = ImageIO.createImageInputStream(getPhoto); BufferedImage bi = ImageIO.read(imageInput); int width = bi.getWidth() - 100; int height = bi.getHeight() - 100; pictureRun.addBreak(); pictureRun.addPicture(getImage, XWPFDocument.PICTURE_TYPE_PNG, null, Units.toEMU(width), Units.toEMU(height)); pictureHolder.setBorderBottom(Borders.BASIC_BLACK_DASHES); pictureHolder.setBorderTop(Borders.BASIC_BLACK_DASHES); pictureHolder.setBorderLeft(Borders.BASIC_BLACK_DASHES); pictureHolder.setBorderRight(Borders.BASIC_BLACK_DASHES); pictureHolder.setAlignment(ParagraphAlignment.CENTER); // pictureRowHolder.getCell(0).setText("IMAGE PLACER"); //Case number and Date XWPFParagraph info = document.createParagraph(); XWPFRun caseNoAndDate = info.createRun(); caseNoAndDate.setText("Case Number: " + galleryResults.getCaseNo()); caseNoAndDate.addTab(); caseNoAndDate.addTab(); caseNoAndDate.addTab(); caseNoAndDate.addTab(); caseNoAndDate.setText(galleryResults.getDate()); caseNoAndDate.setFontSize(16); //Sketch Details XWPFParagraph caseDetails = document.createParagraph(); XWPFRun detailsParagraph = caseDetails.createRun(); detailsParagraph.setText("Offense/Incident: " + galleryResults.getOffenseIncident()); detailsParagraph.addBreak(); detailsParagraph.setText("Name/AKA: " + galleryResults.getNameAKA()); detailsParagraph.addBreak(); detailsParagraph.setText("Sex: " + galleryResults.getSex()); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.setText("Age: " + galleryResults.getAge()); detailsParagraph.addBreak(); detailsParagraph.setText("Height: " + galleryResults.getHeight()); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.setText("Weight: " + galleryResults.getWeight()); detailsParagraph.addBreak(); detailsParagraph.setText("Built: " + galleryResults.getBuilt()); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.addTab(); detailsParagraph.setText("Complexion: " + galleryResults.getComplexion()); detailsParagraph.addBreak(); detailsParagraph.setText("Other Information: " + galleryResults.getOtherInfo()); detailsParagraph.addBreak(); detailsParagraph.setText("Described by: " + galleryResults.getDescribedBy()); detailsParagraph.addBreak(); detailsParagraph.setText("Requesting party: " + galleryResults.getRequestingParty()); //Details Borders caseDetails.setBorderBottom(Borders.BASIC_BLACK_DASHES); caseDetails.setBorderTop(Borders.BASIC_BLACK_DASHES); caseDetails.setBorderLeft(Borders.BASIC_BLACK_DASHES); caseDetails.setBorderRight(Borders.BASIC_BLACK_DASHES); caseDetails.setAlignment(ParagraphAlignment.LEFT); //Reference Paragraph XWPFParagraph outsideDetails = document.createParagraph(); XWPFRun outsideDetailsRun = outsideDetails.createRun(); outsideDetailsRun.addBreak(); outsideDetailsRun.setText("Note: For reference"); outsideDetailsRun.addBreak(); outsideDetailsRun.setText("The witness indicates that this image is: " + galleryResults.getRating()); getPhoto.close(); getImage.close(); imageInput.close(); document.getXWPFDocument(); } catch (IOException | InvalidFormatException e) { e.printStackTrace(); } return document; }