List of usage examples for java.awt Image getHeight
public abstract int getHeight(ImageObserver observer);
From source file:ImageBouncer.java
public ImageBouncer(Image image) { previousTimes = new long[128]; previousTimes[0] = System.currentTimeMillis(); previousIndex = 1;/*www . j av a 2 s. c o m*/ previousFilled = false; mOriginalImage = image; setImageType("TYPE_INT_RGB"); Random random = new Random(); mX = random.nextFloat() * 500; mY = random.nextFloat() * 500; mWidth = image.getWidth(this); mHeight = image.getHeight(this); mDeltaX = random.nextFloat() * 3; mDeltaY = random.nextFloat() * 3; // Make sure points are within range. addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent ce) { Dimension d = getSize(); if (mX < 0) mX = 0; else if (mX + mWidth >= d.width) mX = d.width - mWidth - 1; if (mY < 0) mY = 0; else if (mY + mHeight >= d.height) mY = d.height - mHeight - 1; } }); }
From source file:org.apache.fop.afp.AFPGraphics2D.java
/** {@inheritDoc} */ @Override/*from www .j a va 2s .com*/ public boolean drawImage(Image img, int x, int y, ImageObserver observer) { return drawImage(img, x, y, img.getWidth(observer), img.getHeight(observer), observer); }
From source file:com.cubusmail.server.services.RetrieveImageServlet.java
/** * @param bufInputStream/*from w ww . j ava 2s. c o m*/ * @param outputStream */ private void writeScaledImage(BufferedInputStream bufInputStream, OutputStream outputStream) { long millis = System.currentTimeMillis(); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = bufInputStream.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); } bos.close(); byte[] imageBytes = bos.toByteArray(); Image image = Toolkit.getDefaultToolkit().createImage(imageBytes); MediaTracker mediaTracker = new MediaTracker(new Container()); mediaTracker.addImage(image, 0); mediaTracker.waitForID(0); // determine thumbnail size from WIDTH and HEIGHT int thumbWidth = 300; int thumbHeight = 200; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } // draw original image to thumbnail image object and // scale it to the new size on-the-fly BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 70; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); } catch (IOException ex) { log.error(ex.getMessage(), ex); } catch (InterruptedException ex) { log.error(ex.getMessage(), ex); } finally { log.debug("Time for thumbnail: " + (System.currentTimeMillis() - millis) + "ms"); } }
From source file:org.bigbluebuttonproject.fileupload.document.impl.FileSystemSlideManager.java
/** * This method create thumbImage of the image file given and save it in outFile. * Compression quality is also given. thumbBounds is used for calculating the size of the thumb. * // www . j a v a 2 s . co m * @param infile slide image to create thumb * @param outfile output thumb file * @param compressionQuality the compression quality * @param thumbBounds the thumb bounds * * @throws IOException Signals that an I/O exception has occurred. */ public void resizeImage(File infile, File outfile, float compressionQuality, int thumbBounds) throws IOException { // Retrieve jpg image to be resized Image image = ImageIO.read(infile); // get original image size for thumb size calculation int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); float thumbRatio = (float) thumbBounds / Math.max(imageWidth, imageHeight); int thumbWidth = (int) (imageWidth * thumbRatio); int thumbHeight = (int) (imageHeight * thumbRatio); // draw original image to thumbnail image object and // scale it to the new size on-the-fly BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // Find a jpeg writer ImageWriter writer = null; Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg"); if (iter.hasNext()) { writer = (ImageWriter) iter.next(); } ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(compressionQuality); // Prepare output file ImageOutputStream ios = ImageIO.createImageOutputStream(outfile); writer.setOutput(ios); // write to the thumb image writer.write(thumbImage); // Cleanup ios.flush(); writer.dispose(); ios.close(); }
From source file:org.sbs.util.ImageCompress.java
/** * @param originalFile//from w ww . j av a 2 s . c o m * ? * @param resizedFile * ?? * @param width * ? * @param height * ? -1? * @param format * ? jpg, png, gif(?) * @throws IOException */ public void resize(File originalFile, File resizedFile, int width, int height, String format) throws IOException { if (format != null && "gif".equals(format.toLowerCase())) { resize(originalFile, resizedFile, width, height, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage(in); waitForImage(inputImage); int imageWidth = inputImage.getWidth(null); if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range"); int imageHeight = inputImage.getHeight(null); if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range"); // Create output image. if (height == -1) { double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >= 0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } } Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT); checkImage(outputImage); encode(new FileOutputStream(resizedFile), outputImage, format); }
From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java
public void parse(Image image, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { TemporaryResources tmp = new TemporaryResources(); FileOutputStream fos = null;//from ww w.j a v a 2 s .c o m TikaInputStream tis = null; try { int w = image.getWidth(null); int h = image.getHeight(null); BufferedImage bImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); File file = tmp.createTemporaryFile(); fos = new FileOutputStream(file); ImageIO.write(bImage, "png", fos); tis = TikaInputStream.get(file); parse(tis, handler, metadata, context); } finally { tmp.dispose(); if (tis != null) tis.close(); if (fos != null) fos.close(); } }
From source file:org.apache.fop.render.pdf.pdfbox.PSPDFGraphics2D.java
@Override public boolean drawImage(Image img, int x1, int y1, ImageObserver observer) { PSGenerator tmp = gen;// w w w .j a v a 2 s . c o m if (gen instanceof PSDocumentHandler.FOPPSGenerator) { PSDocumentHandler.FOPPSGenerator fopGen = (PSDocumentHandler.FOPPSGenerator) tmp; PSDocumentHandler handler = fopGen.getHandler(); if (handler.getPSUtil().isOptimizeResources()) { try { final int width = img.getWidth(observer); final int height = img.getHeight(observer); if (width == -1 || height == -1) { return false; } BufferedImage buf = getImage(width, height, img, observer); if (buf == null) { return false; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataBufferInt db = (DataBufferInt) buf.getRaster().getDataBuffer(); DataOutputStream dos = new DataOutputStream(bos); dos.writeInt(width); dos.writeInt(height); for (int i : db.getData()) { dos.writeInt(i); } String format = DataBufferInt.class.getName(); int hash = Arrays.hashCode(bos.toByteArray()); URI uri = fopGen.getImages().get(hash); if (uri == null) { uri = new TempResourceURIGenerator("img" + hash + "." + format).generate(); fopGen.getImages().put(hash, uri); BufferedOutputStream outputStream = fopGen.getTempStream(uri); outputStream.write(bos.toByteArray()); outputStream.close(); } PSResource form = handler.getFormForImage(uri.toASCIIString()); ImageInfo info = new ImageInfo(uri.toASCIIString(), "image/" + format); ImageSize size = new ImageSize(width, height, handler.getUserAgent().getTargetResolution()); size.calcSizeFromPixels(); info.setSize(size); float res = handler.getUserAgent().getSourceResolution() / 72; Rectangle rect = new Rectangle(0, 0, (int) (size.getWidthMpt() * res), (int) (size.getHeightMpt() * res)); gen.saveGraphicsState(); gen.concatMatrix(getTransform()); writeClip(getClip()); PSImageUtils.drawForm(form, info, rect, gen); gen.restoreGraphicsState(); } catch (IOException e) { throw new RuntimeException(e); } return true; } } return super.drawImage(img, x1, y1, observer); }
From source file:com.shending.support.CompressPic.java
public String compressPic() { try {// w ww. ja v a 2 s. c o m // ? file = new File(inputDir); //System.out.println(inputDir + inputFileName); if (!file.exists()) { //throw new Exception("?"); } Image img = ImageIO.read(file); // ?? if (img.getWidth(null) == -1) { System.out.println(" can't read,retry!" + "<BR>"); return "no"; } else { int newWidth; int newHeight; // ? if (this.proportion == true) { // ? double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1; double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1; // ? double rate = rate1 > rate2 ? rate1 : rate2; newWidth = (int) (((double) img.getWidth(null)) / rate); newHeight = (int) (((double) img.getHeight(null)) / rate); } else { newWidth = outputWidth; // newHeight = outputHeight; // } BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB); /* * Image.SCALE_SMOOTH ? ?? */ tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null); File f = new File(outputDir); if (!f.exists()) { f.mkdirs(); } FileOutputStream out = new FileOutputStream(outputDir + outputFileName); // JPEGImageEncoder?? JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } } catch (IOException ex) { ex.printStackTrace(); } return "ok"; }
From source file:gda.plots.SimpleXYItemRenderer.java
/** * Draws the visual representation of a single data item. This mostly reproduces the code of StandardXYItemRenderer * but using the line by line information stored in the SimpleXYSeries instead of the series indexed information * stored in the Renderer itself./* w w w. j a v a 2s . com*/ * * @param g2 * the graphics device. * @param state * the renderer state. * @param dataArea * the area within which the data is being drawn. * @param info * collects information about the drawing. * @param plot * the plot (can be used to obtain standard color information etc). * @param domainAxis * the domain axis. * @param rangeAxis * the range axis. * @param dataset * the dataset. * @param series * the series index (zero-based). * @param item * the item index (zero-based). * @param crosshairState * crosshair information for the plot ( <code>null</code> permitted). * @param pass * the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { SimpleXYSeries sxys = (SimpleXYSeries) ((SimpleXYSeriesCollection) dataset).getSeries(series); if (!sxys.isVisible()) { return; } // setup for collecting optional entity info... Shape entityArea = null; EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } PlotOrientation orientation = plot.getOrientation(); g2.setPaint(sxys.getPaint()); g2.setStroke(sxys.getStroke()); // get the data point double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); // Test x1 = xValueTransformer.transformValue(x1); if (Double.isNaN(x1) || Double.isNaN(y1)) { return; } RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation); if (sxys.isDrawLines()) { if (item > 0) { // get the previous data point... double x0 = dataset.getXValue(series, item - 1); double y0 = dataset.getYValue(series, item - 1); // Test // System.out.print("tranformed " + x0); x0 = xValueTransformer.transformValue(x0); // Message.debug(" to " + x0); if (!Double.isNaN(x0) && !Double.isNaN(y0)) { boolean drawLine = true; if (getPlotDiscontinuous()) { // only draw a line if the gap between the current and // previous data // point is within the threshold int numX = dataset.getItemCount(series); double minX = dataset.getXValue(series, 0); double maxX = dataset.getXValue(series, numX - 1); drawLine = (x1 - x0) <= ((maxX - minX) / numX * getGapThreshold()); } if (drawLine) { double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation); double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation); // only draw if we have good values if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1) || Double.isNaN(transY1)) { return; } if (orientation == PlotOrientation.HORIZONTAL) { state.workingLine.setLine(transY0, transX0, transY1, transX1); } else if (orientation == PlotOrientation.VERTICAL) { state.workingLine.setLine(transX0, transY0, transX1, transY1); } if (state.workingLine.intersects(dataArea)) { g2.draw(state.workingLine); } } } } } if (sxys.isDrawMarkers()) { Shape shape = sxys.getSymbol(); if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1); } else if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1); } if (shape.intersects(dataArea)) { g2.setPaint(sxys.getSymbolPaint()); // Always use full stroke for drawing marker g2.setStroke(new BasicStroke()); if (sxys.getFilled()) { g2.fill(shape); } else { g2.draw(shape); } g2.setPaint(sxys.getPaint()); g2.setStroke(sxys.getStroke()); } entityArea = shape; } if (getPlotImages()) { // use shape scale with transform?? // double scale = getShapeScale(plot, series, item, transX1, // transY1); Image image = getImage(plot, series, item, transX1, transY1); if (image != null) { Point hotspot = getImageHotspot(plot, series, item, transX1, transY1, image); g2.drawImage(image, (int) (transX1 - hotspot.getX()), (int) (transY1 - hotspot.getY()), null); entityArea = new Rectangle2D.Double(transX1 - hotspot.getX(), transY1 - hotspot.getY(), image.getWidth(null), image.getHeight(null)); } } // draw the item label if there is one... if (isItemLabelVisible(series, item)) { drawItemLabel(g2, orientation, dataset, series, item, transX1, transY1, (y1 < 0.0)); } updateCrosshairValues(crosshairState, x1, y1, transX1, transY1, orientation); // add an entity for the item... if (entities != null) { addEntity(entities, entityArea, dataset, series, item, transX1, transY1); } }
From source file:msi.gama.outputs.layers.charts.FastXYItemRenderer.java
/** {@inheritDoc} */ @Override//from w w w .ja va 2 s . c o m public void drawItem(final Graphics2D g2, final XYItemRendererState state, final Rectangle2D dataArea, final PlotRenderingInfo info, final XYPlot plot, final ValueAxis domainAxis, final ValueAxis rangeAxis, final XYDataset dataset, final int series, final int item, final CrosshairState crosshairState, final int pass) { if (!getItemVisible(series, item)) { return; } // setup for collecting optional entity info... boolean bAddEntity = false; Shape entityArea = null; EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } final PlotOrientation orientation = plot.getOrientation(); final Paint paint = getItemPaint(series, item); final Stroke seriesStroke = getItemStroke(series, item); g2.setPaint(paint); g2.setStroke(seriesStroke); // get the data point... final double x1 = dataset.getXValue(series, item); final double y1 = dataset.getYValue(series, item); if (Double.isNaN(x1) || Double.isNaN(y1)) { return; } final RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); final RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); final double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); final double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation); if (getPlotLines()) { if (item == 0) { if (this.drawSeriesLineAsPath) { final State s = (State) state; s.seriesPath.reset(); s.lastPointGood = false; } previousDrawnItem = 0; } if (this.drawSeriesLineAsPath) { final State s = (State) state; // update path to reflect latest point if (!Double.isNaN(transX1) && !Double.isNaN(transY1)) { float x = (float) transX1; float y = (float) transY1; if (orientation == PlotOrientation.HORIZONTAL) { x = (float) transY1; y = (float) transX1; } if (s.isLastPointGood()) { // TODO: check threshold s.seriesPath.lineTo(x, y); } else { s.seriesPath.moveTo(x, y); } s.setLastPointGood(true); } else { s.setLastPointGood(false); } if (item == dataset.getItemCount(series) - 1) { // draw path g2.setStroke(getSeriesStroke(series)); g2.setPaint(getSeriesPaint(series)); g2.draw(s.seriesPath); } } else if (item != 0) { // get the previous data point... final double x0 = dataset.getXValue(series, item - previousDrawnItem); final double y0 = dataset.getYValue(series, item - previousDrawnItem); if (!Double.isNaN(x0) && !Double.isNaN(y0)) { boolean drawLine = true; if (getPlotDiscontinuous()) { // only draw a line if the gap between the current and // previous data point is within the threshold final int numX = dataset.getItemCount(series); final double minX = dataset.getXValue(series, 0); final double maxX = dataset.getXValue(series, numX - 1); if (this.gapThresholdType == UnitType.ABSOLUTE) { drawLine = Math.abs(x1 - x0) <= this.gapThreshold; } else { drawLine = Math.abs(x1 - x0) <= (maxX - minX) / numX * getGapThreshold(); } } if (drawLine) { final double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation); final double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation); // only draw if we have good values if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1) || Double.isNaN(transY1)) { return; } // Only draw line if it is more than a pixel away from the previous one if (transX1 - transX0 > 2 || transX1 - transX0 < -2 || transY1 - transY0 > 2 || transY1 - transY0 < -2 || 0 == previousDrawnItem) { previousDrawnItem = 1; if (orientation == PlotOrientation.HORIZONTAL) { state.workingLine.setLine(transY0, transX0, transY1, transX1); } else if (orientation == PlotOrientation.VERTICAL) { state.workingLine.setLine(transX0, transY0, transX1, transY1); } if (state.workingLine.intersects(dataArea)) { g2.draw(state.workingLine); } } else { // Increase counter for the previous drawn item. previousDrawnItem++; bAddEntity = false; } } } } } if (getBaseShapesVisible()) { Shape shape = getItemShape(series, item); if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1); } else if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1); } if (shape.intersects(dataArea)) { bAddEntity = true; if (getItemShapeFilled(series, item)) { g2.fill(shape); } else { g2.draw(shape); } } entityArea = shape; } if (getPlotImages()) { final Image image = getImage(plot, series, item, transX1, transY1); if (image != null) { final Point hotspot = getImageHotspot(plot, series, item, transX1, transY1, image); g2.drawImage(image, (int) (transX1 - hotspot.getX()), (int) (transY1 - hotspot.getY()), null); entityArea = new Rectangle2D.Double(transX1 - hotspot.getX(), transY1 - hotspot.getY(), image.getWidth(null), image.getHeight(null)); } } // draw the item label if there is one... if (isItemLabelVisible(series, item)) { double xx = transX1; double yy = transY1; if (orientation == PlotOrientation.HORIZONTAL) { xx = transY1; yy = transX1; } drawItemLabel(g2, orientation, dataset, series, item, xx, yy, y1 < 0.0); } updateCrosshairValues(crosshairState, x1, y1, transX1, transY1, orientation); // add an entity for the item... if (entities != null && bAddEntity) { addEntity(entities, entityArea, dataset, series, item, transX1, transY1); } }