List of usage examples for java.awt Image getWidth
public abstract int getWidth(ImageObserver observer);
From source file:com.jflyfox.modules.filemanager.FileManager.java
private Dimension getImageSize(String path) { Dimension imgData = new Dimension(); Image img = new ImageIcon(path).getImage(); imgData.height = img.getHeight(null); imgData.width = img.getWidth(null); return imgData; }
From source file:com.tur0kk.facebook.FacebookClient.java
public String publishPicture(String msg, Image image, String placeId) throws IOException { OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.facebook.com/v2.2/me/photos"); // request node request.addHeader("Authorization", "Bearer " + accesTokenString); // authentificate // check input to avoid error responses if (msg != null && image != null) { // facebook requires multipart post structure MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("message", msg); // description if (placeId != null && !"".equals(placeId)) { builder.addTextBody("place", placeId); // add link to FabLab site if property is set in preferences }/*from w ww. j a va2s . co m*/ // convert image to bytearray and append to multipart BufferedImage bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D bGr = bimage.createGraphics(); bGr.drawImage(image, 0, 0, null); bGr.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bimage, "png", baos); builder.addBinaryBody(msg, baos.toByteArray(), ContentType.MULTIPART_FORM_DATA, "test.png"); // generate multipart byte stream and add to payload of post package HttpEntity multipart = builder.build(); ByteArrayOutputStream multipartOutStream = new ByteArrayOutputStream( (int) multipart.getContentLength()); multipart.writeTo(multipartOutStream); request.addPayload(multipartOutStream.toByteArray()); // set header of post package Header contentType = multipart.getContentType(); request.addHeader(contentType.getName(), contentType.getValue()); // send and response answer Response response = request.send(); return response.getBody(); } else { throw new RuntimeException("message and image needed"); } }
From source file:de.tuttas.restful.SchuelerManager.java
/** * Bild eines Schlers hochladen//from w ww . j av a 2 s .c om * @param idschueler ID des Schlers (wird zum Filenamen) * @param uploadedInputStream InputStream * @param fileDetail Original File Name etc. * @return Ergebnisobjekt mit Meldungen */ @POST @Path("/bild/{idschueler}") @Consumes(MediaType.MULTIPART_FORM_DATA) public ResultObject uploadFile(@PathParam("idschueler") int idschueler, @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { ResultObject r = new ResultObject(); String fileLocation = Config.getInstance().IMAGE_FILE_PATH + idschueler + ".jpg"; Log.d("upload File for " + idschueler); try { byte[] imageBytes = IOUtils.toByteArray(uploadedInputStream); int i = uploadedInputStream.read(imageBytes); Log.d("habe " + i + " bytes gelesen!"); InputStream myInputStream = new ByteArrayInputStream(imageBytes); Image image = ImageIO.read(myInputStream); Log.d("Image gelesen =" + image); InputStream myExifInputStream = new ByteArrayInputStream(imageBytes); int orientation = ImageUtil.getImageOrientation(myExifInputStream); BufferedImage bImage = ImageUtil.toBufferedImage(image); Log.d("Image hat w=" + bImage.getWidth() + " h=" + bImage.getHeight()); bImage = ImageUtil.transformImage(bImage, ImageUtil.getExifTransformation(orientation, image.getWidth(null), image.getHeight(null))); Log.d("Image hat nach Transformation w=" + bImage.getWidth() + " h=" + bImage.getHeight()); if (image != null) { int originalWidth = bImage.getWidth(); int originalHeight = bImage.getHeight(); int newWidth = 200; int newHeight = Math.round(newWidth * ((float) originalHeight / originalWidth)); BufferedImage bi = this.createResizedCopy(bImage, newWidth, newHeight, true); ImageIO.write(bi, "jpg", new File(Config.getInstance().IMAGE_FILE_PATH + idschueler + ".jpg")); r.setMsg("Bild erfolgreich hochgeladen!"); r.setSuccess(true); } else { r.setMsg("Fehler beim Hochladen des Bildes!"); r.setSuccess(false); } } catch (IOException e) { Log.d("Error"); r.setMsg(e.getMessage()); r.setSuccess(false); } catch (MetadataException ex) { Logger.getLogger(SchuelerManager.class.getName()).log(Level.SEVERE, null, ex); } catch (ImageProcessingException ex) { Logger.getLogger(SchuelerManager.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(SchuelerManager.class.getName()).log(Level.SEVERE, null, ex); } return r; }
From source file:com.frochr123.fabqr.gui.FabQRUploadDialog.java
private void btnPhotoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPhotoActionPerformed // Get latest full camera image (without resize) latestFullCameraImage = null;/*from w ww .j av a 2 s . co m*/ if (cameraThread != null) { Image image = cameraThread.getLatestRawImage(); // Convert image to bufferedimage if (image != null) { BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = bufferedImage.createGraphics(); graphics.drawImage(image, 0, 0, null); graphics.dispose(); latestFullCameraImage = bufferedImage; } } // Stop camera, freeze image closeCamera(); // Set correct UI button states btnPhoto.setEnabled(false); btnPhotoRedo.setEnabled(true); btnPublish.setEnabled(true); }
From source file:org.trade.ui.chart.renderer.MACDItemRenderer.java
public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, double x0, double y0, double x1, double y1, int lastItem, int series, int item, CrosshairState crosshairState, int pass, int numX, double minX, double maxX, Paint color, XYDataset dataset) { boolean itemVisible = getItemVisible(series, item); // setup for collecting optional entity info... Shape entityArea = null;// ww w . ja v a2 s. c o m EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } PlotOrientation orientation = plot.getOrientation(); Paint paint = getItemPaint(series, item); paint = color; Stroke seriesStroke = getItemStroke(series, item); g2.setPaint(paint); g2.setStroke(seriesStroke); RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation); if (getPlotLines()) { if (this.drawSeriesLineAsPath) { State s = (State) state; if (s.getSeriesIndex() != series) { // we are starting a new series path s.seriesPath.reset(); s.lastPointGood = false; s.setSeriesIndex(series); } // update path to reflect latest point if (itemVisible && !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 == lastItem) { if (s.seriesIndex == series) { // draw path g2.setStroke(lookupSeriesStroke(series)); g2.setPaint(lookupSeriesPaint(series)); g2.draw(s.seriesPath); } } } else if (item != 0 && itemVisible) { // get the previous data point... 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 if (this.gapThresholdType == UnitType.ABSOLUTE) { drawLine = Math.abs(x1 - x0) <= this.gapThreshold; } else { drawLine = Math.abs(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); } } } } } // we needed to get this far even for invisible items, to ensure that // seriesPath updates happened, but now there is nothing more we need // to do for non-visible items... if (!itemVisible) { return; } 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)) { if (getItemShapeFilled(series, item)) { g2.fill(shape); } else { g2.draw(shape); } } entityArea = shape; } if (getPlotImages()) { 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)); } } double xx = transX1; double yy = transY1; if (orientation == PlotOrientation.HORIZONTAL) { xx = transY1; yy = transX1; } // draw the item label if there is one... if (isItemLabelVisible(series, item)) { drawItemLabel(g2, orientation, dataset, series, item, xx, yy, (y1 < 0.0)); } int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1, transY1, orientation); // add an entity for the item... if (entities != null && isPointInRect(dataArea, xx, yy)) { addEntity(entities, entityArea, dataset, series, item, xx, yy); } }
From source file:net.rptools.maptool.client.ui.ExportDialog.java
/** * Finds the extents of the map, sets up zone to be captured. If the user is * the GM, the extents include every object and everything that has any * area, such as 'fog' and 'visibility' objects. * <p>/*from w w w . j a v a 2s .com*/ * If a background tiling texture is used, the image is aligned to it, so * that it can be used on re-import as a new base map image. * <p> * If the user is a player (or GM posing as a player), the extents only go * as far as the revealed fog-of-war. * <p> * Must be followed by postScreenshot at some point, or the Zone will be * messed up. * * @return the image to be saved */ private PlayerView preScreenshot() throws Exception, OutOfMemoryError { assert (!waitingForPostScreenshot) : "preScreenshot() called twice in a row!"; setupZoneLayers(); boolean viewAsPlayer = ExportRadioButtons.VIEW_PLAYER.isChecked(); // First, figure out the 'extents' of the canvas // This will be later modified by the fog (for players), // and by the tiling texture (for re-importing) // PlayerView view = new PlayerView(viewAsPlayer ? Player.Role.PLAYER : Player.Role.GM); Rectangle extents = renderer.zoneExtents(view); try { // Clip to what the players know about (if applicable). // This keeps the player from exporting the map to learn which // direction has more 'stuff' in it. if (viewAsPlayer) { Rectangle fogE = renderer.fogExtents(); // MapTool.showError(fogE.x + " " + fogE.y + " " + fogE.width + " " + fogE.height); if ((fogE.width < 0) || (fogE.height < 0)) { MapTool.showError(I18N.getString("dialog.screenshot.error.negativeFogExtents")); // Image is not clipped to show only fog-revealed areas!")); } else { extents = extents.intersection(fogE); } } } catch (Exception ex) { throw (new Exception(I18N.getString("dialog.screenshot.error.noArea"), ex)); } if ((extents == null) || (extents.width == 0) || (extents.height == 0)) { throw (new Exception(I18N.getString("dialog.screenshot.error.noArea"))); } // If output includes the tiling 'board' texture, move the upper-left corner // to an integer multiple of the background tile (so it matches up on import). // We don't need to move the lower-right corner because it doesn't matter for // aligning on importing. boolean drawBoard = ExportLayers.LAYER_BOARD.isChecked(); if (drawBoard) { DrawablePaint paint = renderer.getZone().getBackgroundPaint(); DrawableTexturePaint dummy = new DrawableTexturePaint(); Integer tileX = 0, tileY = 0; if (paint.getClass() == dummy.getClass()) { Image bgTexture = ImageManager.getImage(((DrawableTexturePaint) paint).getAsset().getId()); tileX = bgTexture.getWidth(null); tileY = bgTexture.getHeight(null); Integer x = ((int) Math.floor((float) extents.x / tileX)) * tileX; Integer y = ((int) Math.floor((float) extents.y / tileY)) * tileY; extents.width = extents.width + (extents.x - x); extents.height = extents.height + (extents.y - y); extents.x = x; extents.y = y; } } // Save the original state of the renderer to restore later. // Create a place to put the image, and // set up the renderer to encompass the whole extents of the map. origBounds = renderer.getBounds(); origScale = renderer.getZoneScale(); // Setup the renderer to use the new extents Scale s = new Scale(); s.setOffset(-extents.x, -extents.y); renderer.setZoneScale(s); renderer.setBounds(extents); waitingForPostScreenshot = true; return view; }
From source file:AppSpringLayout.java
private BufferedImage toBufferedImage(Image imageToGetBuffered) { if (imageToGetBuffered instanceof BufferedImage) { return (BufferedImage) imageToGetBuffered; }/*from ww w. j a v a 2s . c om*/ // Create a buffered image with transparency BufferedImage bimage = new BufferedImage(imageToGetBuffered.getWidth(null), imageToGetBuffered.getHeight(null), BufferedImage.TYPE_INT_ARGB); return bimage; }
From source file:com.t3.client.ui.ExportDialog.java
/** * Finds the extents of the map, sets up zone to be captured. If the user is * the GM, the extents include every object and everything that has any * area, such as 'fog' and 'visibility' objects. * <p>/* w ww .j av a 2s .com*/ * If a background tiling texture is used, the image is aligned to it, so * that it can be used on re-import as a new base map image. * <p> * If the user is a player (or GM posing as a player), the extents only go * as far as the revealed fog-of-war. * <p> * Must be followed by postScreenshot at some point, or the Zone will be * messed up. * * @return the image to be saved */ private PlayerView preScreenshot() throws Exception, OutOfMemoryError { assert (!waitingForPostScreenshot) : "preScreenshot() called twice in a row!"; setupZoneLayers(); boolean viewAsPlayer = ExportRadioButtons.VIEW_PLAYER.isChecked(); // First, figure out the 'extents' of the canvas // This will be later modified by the fog (for players), // and by the tiling texture (for re-importing) // PlayerView view = new PlayerView(viewAsPlayer ? Player.Role.PLAYER : Player.Role.GM); Rectangle extents = renderer.zoneExtents(view); try { // Clip to what the players know about (if applicable). // This keeps the player from exporting the map to learn which // direction has more 'stuff' in it. if (viewAsPlayer) { Rectangle fogE = renderer.fogExtents(); // TabletopTool.showError(fogE.x + " " + fogE.y + " " + fogE.width + " " + fogE.height); if ((fogE.width < 0) || (fogE.height < 0)) { TabletopTool.showError(I18N.getString("dialog.screenshot.error.negativeFogExtents")); // Image is not clipped to show only fog-revealed areas!")); } else { extents = extents.intersection(fogE); } } } catch (Exception ex) { throw (new Exception(I18N.getString("dialog.screenshot.error.noArea"), ex)); } if ((extents == null) || (extents.width == 0) || (extents.height == 0)) { throw (new Exception(I18N.getString("dialog.screenshot.error.noArea"))); } // If output includes the tiling 'board' texture, move the upper-left corner // to an integer multiple of the background tile (so it matches up on import). // We don't need to move the lower-right corner because it doesn't matter for // aligning on importing. boolean drawBoard = ExportLayers.LAYER_BOARD.isChecked(); if (drawBoard) { DrawablePaint paint = renderer.getZone().getBackgroundPaint(); DrawableTexturePaint dummy = new DrawableTexturePaint(); Integer tileX = 0, tileY = 0; if (paint.getClass() == dummy.getClass()) { Image bgTexture = ImageManager.getImage(((DrawableTexturePaint) paint).getAsset().getId()); tileX = bgTexture.getWidth(null); tileY = bgTexture.getHeight(null); Integer x = ((int) Math.floor((float) extents.x / tileX)) * tileX; Integer y = ((int) Math.floor((float) extents.y / tileY)) * tileY; extents.width = extents.width + (extents.x - x); extents.height = extents.height + (extents.y - y); extents.x = x; extents.y = y; } } // Save the original state of the renderer to restore later. // Create a place to put the image, and // set up the renderer to encompass the whole extents of the map. origBounds = renderer.getBounds(); origScale = renderer.getZoneScale(); // Setup the renderer to use the new extents Scale s = new Scale(); s.setOffset(-extents.x, -extents.y); renderer.setZoneScale(s); renderer.setBounds(extents); waitingForPostScreenshot = true; return view; }
From source file:msi.gama.outputs.layers.charts.StandardXYItemRenderer.java
/** * Returns the hotspot of the image used to draw a single data item. The hotspot is the point relative to the top * left of the image that should indicate the data item. The default is the center of the image. * * @param plot// ww w . j a v a2s. c o m * the plot (can be used to obtain standard color information etc). * @param image * the image (can be used to get size information about the image) * @param series * the series index * @param item * the item index * @param x * the x value of the item * @param y * the y value of the item * * @return The hotspot used to draw the data item. */ protected Point getImageHotspot(final Plot plot, final int series, final int item, final double x, final double y, final Image image) { final int height = image.getHeight(null); final int width = image.getWidth(null); return new Point(width / 2, height / 2); }
From source file:processing.app.Theme.java
/** * Return an Image object from inside the Processing lib folder. *///from w ww. j ava 2 s .c o m static public Image getLibImage(String filename, Component who, int width, int height) { Image image = null; // Use vector image when available Resource vectorFile = getThemeResource(filename + ".svg"); if (vectorFile.exists()) { try { image = imageFromSVG(vectorFile.getUrl(), width, height); } catch (Exception e) { System.err.println("Failed to load " + vectorFile + ": " + e.getMessage()); } } Resource bitmapFile = getThemeResource(filename + ".png"); // Otherwise fall-back to PNG bitmaps, allowing user-defined bitmaps to // override built-in svgs if (image == null || bitmapFile.getPriority() > vectorFile.getPriority()) { Resource bitmap2xFile = getThemeResource(filename + "@2x.png"); Resource imageFile; if (((getScale() > 125 && bitmap2xFile.exists()) || !bitmapFile.exists()) && (bitmapFile.isUserDefined() && bitmap2xFile.isUserDefined())) { imageFile = bitmap2xFile; } else { imageFile = bitmapFile; } Toolkit tk = Toolkit.getDefaultToolkit(); image = tk.getImage(imageFile.getUrl()); } MediaTracker tracker = new MediaTracker(who); try { tracker.addImage(image, 0); tracker.waitForAll(); } catch (InterruptedException e) { } if (image.getWidth(null) != width || image.getHeight(null) != height) { image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); try { tracker.addImage(image, 1); tracker.waitForAll(); } catch (InterruptedException e) { } } return image; }