List of usage examples for java.awt.image BufferedImage getGraphics
public java.awt.Graphics getGraphics()
From source file:at.tuwien.ifs.somtoolbox.apps.viewer.fileutils.ExportUtils.java
public static void saveMapPaneAsImage(GenericPNodeScrollPane mapPane, String imagePath, boolean autoCrop) throws SOMToolboxException { Rectangle r = mapPane.getCanvas().getBounds(); BufferedImage image = new BufferedImage(r.width, r.height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); mapPane.getCanvas().paint(g);//from w w w .ja va 2s. c om if (autoCrop) { image = ImageUtils.autoCrop(image); } FileUtils.saveImageToFile(imagePath, image); }
From source file:com.simiacryptus.util.Util.java
/** * Resize buffered image.// ww w . ja v a2 s. c om * * @param image the image * @return the buffered image */ @Nullable public static BufferedImage resize(@Nullable final BufferedImage image) { if (null == image) return image; final int width = Math.min(image.getWidth(), 800); if (width == image.getWidth()) return image; final int height = image.getHeight() * width / image.getWidth(); @javax.annotation.Nonnull final BufferedImage rerender = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); final Graphics gfx = rerender.getGraphics(); @javax.annotation.Nonnull final RenderingHints hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); ((Graphics2D) gfx).setRenderingHints(hints); gfx.drawImage(image, 0, 0, rerender.getWidth(), rerender.getHeight(), null); return rerender; }
From source file:com.simiacryptus.mindseye.applications.ArtistryUtil.java
/** * Paint lines./*from w w w . j av a 2 s . c o m*/ * * @param canvas the canvas */ public static void paint_Lines(final Tensor canvas) { BufferedImage originalImage = canvas.toImage(); BufferedImage newImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = (Graphics2D) newImage.getGraphics(); IntStream.range(0, 100).forEach(i -> { Random random = new Random(); graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255))); graphics.drawLine(random.nextInt(originalImage.getWidth()), random.nextInt(originalImage.getHeight()), random.nextInt(originalImage.getWidth()), random.nextInt(originalImage.getHeight())); }); canvas.set(Tensor.fromRGB(newImage)); }
From source file:Main.java
private static ByteBuffer convertImageData(BufferedImage bufferedImage) { ByteBuffer imageBuffer;/*from ww w . j a v a 2 s . c o m*/ WritableRaster raster; BufferedImage texImage; // for a texture if (bufferedImage.getColorModel().hasAlpha()) { raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, bufferedImage.getWidth(), bufferedImage.getHeight(), 4, null); texImage = new BufferedImage(glAlphaColorModel, raster, false, new Hashtable<Object, Object>()); } else { raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, bufferedImage.getWidth(), bufferedImage.getHeight(), 3, null); texImage = new BufferedImage(glColorModel, raster, false, new Hashtable<Object, Object>()); } // copy the source image into the produced image Graphics g = texImage.getGraphics(); g.setColor(new Color(0f, 0f, 0f, 0f)); g.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight()); g.drawImage(bufferedImage, 0, 0, null); // build a byte buffer from the temporary image // that be used by OpenGL to produce a texture. byte[] data = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData(); imageBuffer = ByteBuffer.allocateDirect(data.length); imageBuffer.order(ByteOrder.nativeOrder()); imageBuffer.put(data, 0, data.length); imageBuffer.flip(); return imageBuffer; }
From source file:com.simiacryptus.mindseye.applications.ArtistryUtil.java
/** * Paint circles.// w ww . j ava2 s . c o m * * @param canvas the canvas * @param scale the scale */ public static void paint_Circles(final Tensor canvas, final int scale) { BufferedImage originalImage = canvas.toImage(); BufferedImage newImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = (Graphics2D) newImage.getGraphics(); IntStream.range(0, 10000).forEach(i -> { Random random = new Random(); int positionX = random.nextInt(originalImage.getWidth()); int positionY = random.nextInt(originalImage.getHeight()); int width = 1 + random.nextInt(2 * scale); int height = 1 + random.nextInt(2 * scale); DoubleStatistics[] stats = { new DoubleStatistics(), new DoubleStatistics(), new DoubleStatistics() }; canvas.coordStream(false).filter(c -> { int[] coords = c.getCoords(); int x = coords[0]; int y = coords[1]; double relX = Math.pow(1 - 2 * ((double) (x - positionX) / width), 2); double relY = Math.pow(1 - 2 * ((double) (y - positionY) / height), 2); return relX + relY < 1.0; }).forEach(c -> stats[c.getCoords()[2]].accept(canvas.get(c))); graphics.setStroke(new Stroke() { @Override public Shape createStrokedShape(final Shape p) { return null; } }); graphics.setColor(new Color((int) stats[0].getAverage(), (int) stats[1].getAverage(), (int) stats[2].getAverage())); graphics.fillOval(positionX, positionY, width, height); }); canvas.set(Tensor.fromRGB(newImage)); }
From source file:fr.fg.server.core.TerritoryManager.java
private static BufferedImage createTerritoryMap(int idSector) { List<Area> areas = new ArrayList<Area>(DataAccess.getAreasBySector(idSector)); float[][] points = new float[areas.size()][2]; int[] dominatingAllies = new int[areas.size()]; int i = 0;/*from w w w . j a v a 2s. co m*/ for (Area area : areas) { points[i][0] = area.getX() * MAP_SCALE; points[i][1] = area.getY() * MAP_SCALE; dominatingAllies[i] = area.getIdDominatingAlly(); i++; } Hull hull = new Hull(points); MPolygon hullPolygon = hull.getRegion(); float[][] newPoints = new float[points.length + hullPolygon.count()][2]; System.arraycopy(points, 0, newPoints, 0, points.length); float[][] hullCoords = hullPolygon.getCoords(); for (i = 0; i < hullPolygon.count(); i++) { double angle = Math.atan2(hullCoords[i][1], hullCoords[i][0]); double length = Math.sqrt(hullCoords[i][0] * hullCoords[i][0] + hullCoords[i][1] * hullCoords[i][1]); newPoints[i + points.length][0] = (float) (Math.cos(angle) * (length + 8 * MAP_SCALE)); newPoints[i + points.length][1] = (float) (Math.sin(angle) * (length + 8 * MAP_SCALE)); } points = newPoints; Voronoi voronoi = new Voronoi(points); Delaunay delaunay = new Delaunay(points); // Dcoupage en rgions MPolygon[] regions = voronoi.getRegions(); // Calcule le rayon de la galaxie int radius = 0; for (Area area : areas) { radius = Math.max(radius, area.getX() * area.getX() + area.getY() * area.getY()); } radius = (int) Math.floor(Math.sqrt(radius) * MAP_SCALE) + 10 * MAP_SCALE; int diameter = 2 * radius + 1; // Construit l'image avec les quadrants BufferedImage territoriesImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) territoriesImage.getGraphics(); // Affecte une couleur chaque alliance HashMap<Integer, Color> alliesColors = new HashMap<Integer, Color>(); for (Area area : areas) { int idDominatingAlly = area.getIdDominatingAlly(); if (idDominatingAlly != 0) alliesColors.put(idDominatingAlly, Ally.TERRITORY_COLORS[DataAccess.getAllyById(idDominatingAlly).getColor()]); } Polygon[] polygons = new Polygon[regions.length]; for (i = 0; i < areas.size(); i++) { if (dominatingAllies[i] != 0) { polygons[i] = createPolygon(regions[i].getCoords(), radius + 1, 3); } } // Dessine tous les secteurs g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); for (i = 0; i < areas.size(); i++) { if (dominatingAllies[i] == 0) continue; Polygon p = polygons[i]; // Dessine le polygone g.setColor(alliesColors.get(dominatingAllies[i])); g.fill(p); // Rempli les espaces entre les polygones adjacents qui // correspondent au territoire d'une mme alliance int[] linkedRegions = delaunay.getLinked(i); for (int j = 0; j < linkedRegions.length; j++) { int linkedRegion = linkedRegions[j]; if (linkedRegion >= areas.size()) continue; if (dominatingAllies[i] == dominatingAllies[linkedRegion]) { if (linkedRegion <= i) continue; float[][] coords1 = regions[i].getCoords(); float[][] coords2 = regions[linkedRegion].getCoords(); int junctionIndex = 0; int[][] junctions = new int[2][2]; search: for (int k = 0; k < coords1.length; k++) { for (int l = 0; l < coords2.length; l++) { if (coords1[k][0] == coords2[l][0] && coords1[k][1] == coords2[l][1]) { junctions[junctionIndex][0] = k; junctions[junctionIndex][1] = l; junctionIndex++; if (junctionIndex == 2) { int[] xpts = new int[] { polygons[i].xpoints[junctions[0][0]], polygons[linkedRegion].xpoints[junctions[0][1]], polygons[linkedRegion].xpoints[junctions[1][1]], polygons[i].xpoints[junctions[1][0]], }; int[] ypts = new int[] { polygons[i].ypoints[junctions[0][0]], polygons[linkedRegion].ypoints[junctions[0][1]], polygons[linkedRegion].ypoints[junctions[1][1]], polygons[i].ypoints[junctions[1][0]], }; Polygon border = new Polygon(xpts, ypts, 4); g.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND)); g.fill(border); g.draw(border); break search; } break; } } } } } } // Dessine des lignes de contours des territoires g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); for (i = 0; i < areas.size(); i++) { if (dominatingAllies[i] == 0) continue; g.setStroke(new BasicStroke(1.5f)); g.setColor(alliesColors.get(dominatingAllies[i]).brighter().brighter()); float[][] coords1 = regions[i].getCoords(); lines: for (int j = 0; j < coords1.length; j++) { int[] linkedRegions = delaunay.getLinked(i); for (int k = 0; k < linkedRegions.length; k++) { int linkedRegion = linkedRegions[k]; if (linkedRegion >= areas.size()) continue; if (dominatingAllies[i] == dominatingAllies[linkedRegion]) { float[][] coords2 = regions[linkedRegion].getCoords(); for (int m = 0; m < coords2.length; m++) { if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1] && ((coords1[(j + 1) % coords1.length][0] == coords2[(m + 1) % coords2.length][0] && coords1[(j + 1) % coords1.length][1] == coords2[(m + 1) % coords2.length][1]) || (coords1[(j + 1) % coords1.length][0] == coords2[(m - 1 + coords2.length) % coords2.length][0] && coords1[(j + 1) % coords1.length][1] == coords2[(m - 1 + coords2.length) % coords2.length][1]))) { continue lines; } } } } g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]), Math.round(polygons[i].xpoints[(j + 1) % coords1.length]), Math.round(polygons[i].ypoints[(j + 1) % coords1.length])); } for (int j = 0; j < coords1.length; j++) { int neighbours = 0; int lastNeighbourRegion = -1; int neighbourCoordsIndex = -1; int[] linkedRegions = delaunay.getLinked(i); for (int k = 0; k < linkedRegions.length; k++) { int linkedRegion = linkedRegions[k]; if (linkedRegion >= areas.size()) continue; if (dominatingAllies[i] == dominatingAllies[linkedRegion]) { float[][] coords2 = regions[linkedRegion].getCoords(); for (int m = 0; m < coords2.length; m++) { if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]) { neighbours++; lastNeighbourRegion = linkedRegion; neighbourCoordsIndex = m; break; } } } } if (neighbours == 1) { g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]), Math.round(polygons[lastNeighbourRegion].xpoints[neighbourCoordsIndex]), Math.round(polygons[lastNeighbourRegion].ypoints[neighbourCoordsIndex])); } } } BufferedImage finalImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB); g = (Graphics2D) finalImage.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .15f)); g.drawImage(territoriesImage, 0, 0, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f)); // Charge la police pour afficher le nom des alliances try { Font textFont = Font.createFont(Font.TRUETYPE_FONT, Action.class.getClassLoader().getResourceAsStream("fr/fg/server/resources/TinDog.ttf")); textFont = textFont.deriveFont(12f).deriveFont(Font.BOLD); g.setFont(textFont); } catch (Exception e) { LoggingSystem.getServerLogger().warn("Could not load quadrant map font.", e); } FontMetrics fm = g.getFontMetrics(); ArrayList<Integer> closedRegions = new ArrayList<Integer>(); for (i = 0; i < areas.size(); i++) { if (dominatingAllies[i] == 0 || closedRegions.contains(i)) continue; ArrayList<Integer> allyRegions = new ArrayList<Integer>(); ArrayList<Integer> openRegions = new ArrayList<Integer>(); openRegions.add(i); while (openRegions.size() > 0) { int currentRegion = openRegions.remove(0); allyRegions.add(currentRegion); closedRegions.add(currentRegion); int[] linkedRegions = delaunay.getLinked(currentRegion); for (int k = 0; k < linkedRegions.length; k++) { int linkedRegion = linkedRegions[k]; if (linkedRegion >= areas.size() || openRegions.contains(linkedRegion) || allyRegions.contains(linkedRegion)) continue; if (dominatingAllies[i] == dominatingAllies[linkedRegion]) openRegions.add(linkedRegion); } } Area area = areas.get(i); long xsum = 0; long ysum = 0; for (int k = 0; k < allyRegions.size(); k++) { int allyRegion = allyRegions.get(k); area = areas.get(allyRegion); xsum += area.getX(); ysum += area.getY(); } int x = (int) (xsum / allyRegions.size()) * MAP_SCALE + radius + 1; int y = (int) (-ysum / allyRegions.size()) * MAP_SCALE + radius + 1; ; Point point = new Point(x, y); boolean validLocation = false; for (int k = 0; k < allyRegions.size(); k++) { int allyRegion = allyRegions.get(k); if (polygons[allyRegion].contains(point)) { validLocation = true; break; } } if (validLocation) { if (allyRegions.size() == 1) y -= 14; } else { int xmid = (int) (xsum / allyRegions.size()); int ymid = (int) (ysum / allyRegions.size()); area = areas.get(i); int dx = area.getX() - xmid; int dy = area.getY() - ymid; int distance = dx * dx + dy * dy; int nearestAreaIndex = i; int nearestDistance = distance; for (int k = 0; k < allyRegions.size(); k++) { int allyRegion = allyRegions.get(k); area = areas.get(allyRegion); dx = area.getX() - xmid; dy = area.getY() - ymid; distance = dx * dx + dy * dy; if (distance < nearestDistance) { nearestAreaIndex = allyRegion; nearestDistance = distance; } } area = areas.get(nearestAreaIndex); x = area.getX() * MAP_SCALE + radius + 1; y = -area.getY() * MAP_SCALE + radius - 13; } // Dessine le tag de l'alliance String allyTag = "[ " + DataAccess.getAllyById(dominatingAllies[i]).getTag() + " ]"; g.setColor(Color.BLACK); g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2 + 1, y); g.setColor(alliesColors.get(dominatingAllies[i])); g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2, y); } return finalImage; }
From source file:gr.iti.mklab.reveal.forensics.util.Util.java
public static BufferedImage scaleImage(BufferedImage image, int width, int height) { assert (width > 0 && height > 0); // create image of new size BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = img.getGraphics(); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); // ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(image, 0, 0, img.getWidth(), img.getHeight(), null); return img;//from w w w . ja v a 2 s . c om }
From source file:org.openstreetmap.josm.tools.ImageProvider.java
/** * Creates a rotated version of the input image. * * @param c The component to get properties useful for painting, e.g. the foreground or * background color./* w w w . j a v a 2 s .c om*/ * @param img the image to be rotated. * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we * will mod it with 360 before using it. * * @return the image after rotating. */ public static Image createRotatedImage(Component c, Image img, double rotatedAngle) { // convert rotatedAngle to a value from 0 to 360 double originalAngle = rotatedAngle % 360; if (rotatedAngle != 0 && originalAngle == 0) { originalAngle = 360.0; } // convert originalAngle to a value from 0 to 90 double angle = originalAngle % 90; if (originalAngle != 0.0 && angle == 0.0) { angle = 90.0; } double radian = Math.toRadians(angle); new ImageIcon(img); // load completely int iw = img.getWidth(null); int ih = img.getHeight(null); int w; int h; if ((originalAngle >= 0 && originalAngle <= 90) || (originalAngle > 180 && originalAngle <= 270)) { w = (int) (iw * Math.sin(DEGREE_90 - radian) + ih * Math.sin(radian)); h = (int) (iw * Math.sin(radian) + ih * Math.sin(DEGREE_90 - radian)); } else { w = (int) (ih * Math.sin(DEGREE_90 - radian) + iw * Math.sin(radian)); h = (int) (ih * Math.sin(radian) + iw * Math.sin(DEGREE_90 - radian)); } BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics g = image.getGraphics(); Graphics2D g2d = (Graphics2D) g.create(); // calculate the center of the icon. int cx = iw / 2; int cy = ih / 2; // move the graphics center point to the center of the icon. g2d.translate(w / 2, h / 2); // rotate the graphics about the center point of the icon g2d.rotate(Math.toRadians(originalAngle)); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.drawImage(img, -cx, -cy, c); g2d.dispose(); new ImageIcon(image); // load completely return image; }
From source file:org.eclipse.wb.internal.swing.utils.SwingImageUtils.java
/** * Traverses through components hierarchy and prepares screen shot for every component passed in * <code>componentImages</code> map except for branch root if <code>isRoot</code> is * <code>true</code>.//from w w w . j a v a 2 s . c om * * @param component * the branch hierarchy root component. * @param componentImages * the {@link Map} of components which screen shots should be made for. This map would be * filled by prepared {@link java.awt.Image} instances. * @param rootComponent * this branch hierarchy root component. */ static void makeShotsHierarchy(Component component, Map<Component, java.awt.Image> componentImages, Component rootComponent) throws Exception { if (componentImages.containsKey(component) && component != rootComponent) { BufferedImage thisComponentImage = (BufferedImage) createComponentShotAWT(component); // BUG in OS X (Java 1.6.0_24-b07-334-10M3326): Component.printAll() returns no image // for AWT components and these components are not drawn on the JComponent container // using the same printAll() method. // The workaround is to hack into a native peer, get the native image and then paint it. if (EnvironmentUtils.IS_MAC && !(component instanceof JComponent)) { int width = Math.max(1, component.getWidth()); int height = Math.max(1, component.getHeight()); Image nativeImage = OSSupport.get().makeShotAwt(component, width, height); if (nativeImage != null) { BufferedImage rootImage = (BufferedImage) componentImages.get(rootComponent); Point rootLocation = rootComponent.getLocationOnScreen(); Point componentLocation = component.getLocationOnScreen(); thisComponentImage = ImageUtils.convertToAWT(nativeImage.getImageData()); rootImage.getGraphics().drawImage(thisComponentImage, componentLocation.x - rootLocation.x, componentLocation.y - rootLocation.y, null); } } componentImages.put(component, thisComponentImage); } if (component instanceof Container) { Container container = (Container) component; for (Component childComponent : container.getComponents()) { makeShotsHierarchy(childComponent, componentImages, rootComponent); } } }
From source file:net.cbtltd.server.UploadFileService.java
private static byte[] getImageBlob(String fn, int fullsizepixels) { try {//from ww w . ja va2 s. c o m ImageIcon image = new ImageIcon(fn); ImageIcon logoImage = new ImageIcon( image.getImage().getScaledInstance(fullsizepixels, -1, Image.SCALE_SMOOTH)); BufferedImage bufferedImage = new BufferedImage(logoImage.getIconWidth(), logoImage.getIconHeight(), BufferedImage.TYPE_INT_RGB); Graphics graphics = bufferedImage.getGraphics(); graphics.drawImage(logoImage.getImage(), 0, 0, null); fn = fn.substring(0, fn.lastIndexOf('.')) + ".Blob.jpg"; File file = new File(fn); file.delete(); ImageIO.write(bufferedImage, FULLSIZE_JPEG, file); InputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { throw new IOException("File is too large for logo - maximum size = " + Integer.MAX_VALUE); } byte[] bytes = new byte[(int) length]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException("Could not completely read file " + file.getName()); } is.close(); return bytes; } catch (IOException x) { throw new RuntimeException("Error creating BLOB image " + x.getMessage()); } }