/** * Simple image flipper. Can flip image either vertically, horizontally or both directions * * @param source _ * @param flipType _ * @return BufferedImage * @throws NullPointerException _ * @throws IllegalArgumentException _ */ public static <T> BufferedImage flipImage(final T source, final FlipType flipType) throws NullPointerException, IllegalArgumentException, IOException { if (verifyNotNull(source, flipType)) { BufferedImage sourceImage = convertToBufferedImage(source); BufferedImage target = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType()); AffineTransform affineTransform; AffineTransformOp affineTransformOp; if (flipType.equals(FlipType.HORIZONTAL) || flipType.equals(FlipType.BOTH)) { affineTransform = AffineTransform.getScaleInstance(1, -1); affineTransform.translate(-sourceImage.getWidth(), 0); affineTransformOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); target = affineTransformOp.filter(sourceImage, target); } if (flipType.equals(FlipType.VERTICAL) || flipType.equals(FlipType.BOTH)) { affineTransform = AffineTransform.getScaleInstance(1, -1); affineTransformOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); affineTransform.translate(0, -sourceImage.getHeight()); target = affineTransformOp.filter(sourceImage, target); } return target; } throw new NullPointerException(E_OBJECT_WAS_NULL); }
static BufferedImage addMagnitudes(BufferedImage img1, BufferedImage img2) { BufferedImage dst = new BufferedImage(img1.getWidth(), img1.getHeight(), img1.getType()); for (int y = 0; y < img1.getHeight(); ++y) { for (int x = 0; x < img1.getWidth(); ++x) { int rgb1 = img1.getRGB(x, y); int rgb2 = img2.getRGB(x, y); int r1 = (rgb1 & 0x00FF0000) >> 16; int r2 = (rgb2 & 0x00FF0000) >> 16; int r = (int) (Math.sqrt(r1 * r1 + r2 * r2) / Math.sqrt(2.0)); if (r > 255) r = 255; if (r < 0) r = 0; int g1 = (rgb1 & 0x0000FF00) >> 8; int g2 = (rgb2 & 0x0000FF00) >> 8; int g = (int) (Math.sqrt(g1 * g1 + g2 * g2) / Math.sqrt(2.0)); if (g > 255) g = 255; if (g < 0) g = 0; int b1 = rgb1 & 0x000000FF; int b2 = rgb2 & 0x000000FF; int b = (int) (Math.sqrt(b1 * b1 + b2 * b2) / Math.sqrt(2.0)); if (b > 255) b = 255; if (b < 0) b = 0; int rgb = b + (g << 8) + (r << 16); dst.setRGB(x, y, rgb); } } return dst; }
private static ImageElement fetchImageProperties( final BufferedImage source, final ImageType imageType, final String id, final Date modifiedDate, final String mimeType) throws NullPointerException, IOException { if (verifyNotNull(source)) { ImageElement image = new ImageElement(); image.setBitDepth( verifyNotNull(source.getColorModel().getPixelSize()) ? source.getColorModel().getPixelSize() : 0); image.setHeight(verifyNotNull(source.getHeight()) ? source.getHeight() : 0); image.setWidth(verifyNotNull(source.getWidth()) ? source.getWidth() : 0); image.setSizeInBytes(determineSizeOfBufferedImage(source, imageType.toString())); image.setCreated(new Date(System.currentTimeMillis())); image.setTransparent( determineTransparencyType(source.getGraphics().getColor().getTransparency())); if (verifyNotNull(modifiedDate)) image.setModified(modifiedDate); image.setId((verifyNotNull(id) ? id : "")); image.setFontType( verifyNotNull(source.getGraphics().getFont()) ? source.getGraphics().getFont() : new Font("Default", 0, 0)); image.setMediaType(MediaType.Missing); return image; } throw new NullPointerException(E_OBJECT_WAS_NULL); }
/** * Synchronize the textLayout and the shape (=frame box, by calling syncFrame) with the model When * <code>TextLayout</code> is used, this delegates to <code>getRotation()</code> where computing * rotation angle is concerned, and updates the AffineTransform returned by <code> * getTextToModelTransform()</code>. */ protected void syncShape() { PicText te = (PicText) element; // textLayout = new TextLayout(te.getText().length()==0 ? " " : te.getText(), // textFont, // new FontRenderContext(null,false,false)); text2ModelTr.setToIdentity(); // reset PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf); text2ModelTr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR ! // the reference point of an image is the top-left one, but the refpoint of a text layout is on // the baseline if (image != null) { text2ModelTr.translate(te.getLeftX(), te.getTopY()); if (te.getWidth() != 0 && image.getWidth() != 0 && (te.getDepth() + te.getHeight()) != 0 && image.getHeight() != 0) text2ModelTr.scale( te.getWidth() / image.getWidth(), -(te.getHeight() + te.getDepth()) / image.getHeight()); } else { // Hack ? Just cheating a little bit ? Ou juste ruse ? // we want here to use the dimensions of the textLayout instead of latex dimensions if // areDimensionsComputed // sinon on va aligner le textlayout en fonction des parametres latex, et l'Utilisateur (qui // est bien bete) ne va rien comprendre. double latexH = 0; double latexD = 0; double latexW = 0; if (areDimensionsComputed) { // store latex dimensions, and setDimensions to textLayout ones latexH = te.getHeight(); latexD = te.getDepth(); latexW = te.getWidth(); te.setDimensions( textLayout.getBounds().getWidth(), textLayout.getAscent(), textLayout.getDescent()); } text2ModelTr.translate(te.getLeftX(), te.getBaseLineY()); if (areDimensionsComputed) { // restore latex dimensions te.setDimensions(latexW, latexH, latexD); } // Autre possibilite= comprimer le texte pour qu'il rentre dans la boite (evite le hack // ci-dessus): // text2ModelTr.scale(te.getWidth()/textLayout.getWidth(),-(te.getHeight()+te.getDepth())/textLayout.getHeight()); text2ModelTr.scale(1.0, -1.0); } syncFrame(); }
/** * Adds next GIF frame. The frame is not written immediately, but is actually deferred until the * next frame is received so that timing data can be inserted. Invoking <code>finish()</code> * flushes all frames. If <code>setSize</code> was not invoked, the size of the first image is * used for all subsequent frames. * * @param im BufferedImage containing frame to write. * @throws IOException if there was an IOException writing the GIF data * @throws IllegalArgumentException if this encoder has not been started */ public void addFrame(BufferedImage im) throws IOException { if (!started) { throw new IllegalStateException("AnimatedGifEncoder not started"); } if (!sizeSet) { // use first frame's size setSize(im.getWidth(), im.getHeight()); } image = im; getImagePixels(); // convert to correct format if necessary analyzePixels(); // build color table & map pixels if (firstFrame) { writeLSD(); // logical screen descriptior writePalette(); // global color table if (repeat >= 0) { // use NS app extension to indicate reps writeNetscapeExt(); } } writeGraphicCtrlExt(); // write graphic control extension writeImageDesc(); // image descriptor if (!firstFrame) { writePalette(); // local color table } writePixels(); // encode and write pixel data firstFrame = false; }
/** * Adds next GIF frame. The frame is not written immediately, but is actually deferred until the * next frame is received so that timing data can be inserted. Invoking <code>finish()</code> * flushes all frames. If <code>setSize</code> was not invoked, the size of the first image is * used for all subsequent frames. * * @param im BufferedImage containing frame to write. * @return true if successful. */ public boolean addFrame(BufferedImage im) { if ((im == null) || !started) { return false; } boolean ok = true; try { if (!sizeSet) { // use first frame's size setSize(im.getWidth(), im.getHeight()); } image = im; getImagePixels(); // convert to correct format if necessary analyzePixels(); // build color table & map pixels if (firstFrame) { writeLSD(); // logical screen descriptior writePalette(); // global color table if (repeat >= 0) { // use NS app extension to indicate reps writeNetscapeExt(); } } writeGraphicCtrlExt(); // write graphic control extension writeImageDesc(); // image descriptor if (!firstFrame) { writePalette(); // local color table } writePixels(); // encode and write pixel data firstFrame = false; } catch (IOException e) { ok = false; } return ok; }
private <T> T scaleImageUsingAffineTransformation(final BufferedImage bufferedImage, T target) { BufferedImage destinationImage = generateDestinationImage(); Graphics2D graphics2D = destinationImage.createGraphics(); AffineTransform transformation = AffineTransform.getScaleInstance( ((double) getQualifiedWidth() / bufferedImage.getWidth()), ((double) getQualifiedHeight() / bufferedImage.getHeight())); graphics2D.drawRenderedImage(bufferedImage, transformation); graphics2D.addRenderingHints(retrieveRenderingHints()); try { if (target instanceof File) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "File")); ImageIO.write(destinationImage, imageType.toString(), (File) target); } else if (target instanceof ImageOutputStream) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "ImageOutputStream")); ImageIO.write(destinationImage, imageType.toString(), (ImageOutputStream) target); } else if (target instanceof OutputStream) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "OutputStream")); ImageIO.write(destinationImage, imageType.toString(), (OutputStream) target); } else { target = null; } } catch (IOException e) { e.printStackTrace(); } return target; }
public synchronized void paint(Graphics gin) { Graphics2D g = (Graphics2D) gin; if (im == null) return; int height = getHeight(); int width = getWidth(); if (fit) { t = new AffineTransform(); double scale = Math.min(((double) width) / im.getWidth(), ((double) height) / im.getHeight()); // we'll re-center the transform in a moment. t.scale(scale, scale); } // if the image (in either X or Y) is smaller than the view port, then center // the image with respect to that axis. double mwidth = im.getWidth() * t.getScaleX(); double mheight = im.getHeight() * t.getScaleY(); if (mwidth < width) t.preConcatenate( AffineTransform.getTranslateInstance((width - mwidth) / 2.0 - t.getTranslateX(), 0)); if (mheight < height) t.preConcatenate( AffineTransform.getTranslateInstance(0, (height - mheight) / 2.0 - t.getTranslateY())); // if we're allowing panning (because only a portion of the image is visible), // don't allow translations that show less information that is possible. Point2D topleft = t.transform(new Point2D.Double(0, 0), null); Point2D bottomright = t.transform(new Point2D.Double(im.getWidth(), im.getHeight()), null); if (mwidth > width) { if (topleft.getX() > 0) t.preConcatenate(AffineTransform.getTranslateInstance(-topleft.getX(), 0)); if (bottomright.getX() < width) t.preConcatenate(AffineTransform.getTranslateInstance(width - bottomright.getX(), 0)); // t.translate(width-bottomright.getX(), 0); } if (mheight > height) { if (topleft.getY() > 0) t.preConcatenate(AffineTransform.getTranslateInstance(0, -topleft.getY())); if (bottomright.getY() < height) t.preConcatenate(AffineTransform.getTranslateInstance(0, height - bottomright.getY())); } g.drawImage(im, t, null); }
public void drawScaledImage(BufferedImage im, int x, int y, int w, int h) { float scaleX = w * 1.0f / im.getWidth(); float scaleY = h * 1.0f / im.getHeight(); AffineTransform tx = new AffineTransform(); tx.scale(scaleX, scaleY); BufferedImageOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); drawImage(im, op, x, y); }
public static BufferedImage convertToARGB(BufferedImage image) { BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = newImage.createGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return newImage; }
private void scaleImage() { Image img = back.getScaledInstance(scx(back.getWidth()), scy(back.getHeight()), Image.SCALE_SMOOTH); back = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics g = back.getGraphics(); g.drawImage(img, 0, 0, null); g.dispose(); }
public void paint(Graphics g) { // image=tool.getImage(imageName); int h = image2.getHeight(this) / 2; int w = image2.getWidth(this) / 2; g.drawImage(image2, 150, 100, this); // g.drawImage(this.image2, 150+w+30, 100,w,h,this); // g.drawString(imageName, 170, 50); }
private static void initImg(BufferedImage img, int pf, int flags) throws Exception { WritableRaster wr = img.getRaster(); int imgType = img.getType(); if (imgType == BufferedImage.TYPE_INT_RGB || imgType == BufferedImage.TYPE_INT_BGR || imgType == BufferedImage.TYPE_INT_ARGB || imgType == BufferedImage.TYPE_INT_ARGB_PRE) { SinglePixelPackedSampleModel sm = (SinglePixelPackedSampleModel) img.getSampleModel(); int pitch = sm.getScanlineStride(); DataBufferInt db = (DataBufferInt) wr.getDataBuffer(); int[] buf = db.getData(); initIntBuf(buf, img.getWidth(), pitch, img.getHeight(), pf, flags); } else { ComponentSampleModel sm = (ComponentSampleModel) img.getSampleModel(); int pitch = sm.getScanlineStride(); DataBufferByte db = (DataBufferByte) wr.getDataBuffer(); byte[] buf = db.getData(); initBuf(buf, img.getWidth(), pitch, img.getHeight(), pf, flags); } }
public static BufferedImage tileImage(BufferedImage im, int width, int height) { GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment() .getDefaultScreenDevice() .getDefaultConfiguration(); int transparency = Transparency.OPAQUE; // Transparency.BITMASK; BufferedImage compatible = gc.createCompatibleImage(width, height, transparency); Graphics2D g = (Graphics2D) compatible.getGraphics(); g.setPaint(new TexturePaint(im, new Rectangle(0, 0, im.getWidth(), im.getHeight()))); g.fillRect(0, 0, width, height); return compatible; }
public static void main(String[] args) throws Exception { Robot robot = new Robot(args[0]); BufferedImage oimg = robot.cam.capture(true); // BufferedImage img = maslab.camera.ImageUtil.convertImage(oimg, BufferedImage.TYPE_INT_RGB); BufferedImage img = new BufferedImage(oimg.getWidth(), oimg.getHeight(), BufferedImage.TYPE_INT_RGB); for (int y = 0; y < oimg.getHeight(); ++y) { for (int x = 0; x < oimg.getWidth(); ++x) { img.setRGB(x, y, oimg.getRGB(x, y)); } } BufferedImage blurred = gaussianBlur(img); ImageIO.write(blurred, "bmp", new File("gaussian.bmp")); BufferedImage xe = sobelX(blurred); ImageIO.write(xe, "bmp", new File("sobelx.bmp")); BufferedImage ye = sobelY(blurred); ImageIO.write(ye, "bmp", new File("sobely.bmp")); BufferedImage edges = addMagnitudes(xe, ye); BufferedImage dst = edges; ImageIO.write(dst, "bmp", new File("edges.bmp")); }
public static BufferedImage scaleImage(BufferedImage bi, double scale) { int w1 = (int) (Math.round(scale * bi.getWidth())); int h1 = (int) (Math.round(scale * bi.getHeight())); BufferedImage image = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.setPaint(Color.white); g2.fillRect(0, 0, w1, h1); g2.drawImage(bi, 0, 0, w1, h1, null); // this); g2.dispose(); return image; }
/** Extracts image pixels into byte array "pixels" */ protected void getImagePixels() { int w = image.getWidth(); int h = image.getHeight(); int type = image.getType(); if ((w != width) || (h != height) || (type != BufferedImage.TYPE_3BYTE_BGR)) { // create new image with right size/format BufferedImage temp = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); Graphics2D g = temp.createGraphics(); g.drawImage(image, 0, 0, null); image = temp; } pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); }
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { if (image != null && showimage) { // TODO: add ability to scale maintaining aspect ratio fitting to size of parent // TODO: Need to add not zoom all the way, but zoom to a box of aspect ratio 4/3 Graphics2D g2 = (Graphics2D) g; AffineTransform tran = new AffineTransform(1f, 0f, 0f, 1f, 0, 0); float widthscale = (float) c.getWidth() / image.getWidth(); float heightscale = (float) c.getHeight() / image.getHeight(); switch (drawmode) { case DRAW_MODE_ASPECT: float scale; if (widthscale < heightscale) { scale = widthscale; } else { scale = heightscale; } tran.scale(scale, scale); g2.drawImage( image, new AffineTransformOp(tran, AffineTransformOp.TYPE_BILINEAR), (int) (c.getWidth() - image.getWidth() * scale) / 2, (int) (c.getHeight() - image.getHeight() * scale) / 2); break; case DRAW_MODE_WIDTH: tran.scale(widthscale, widthscale); g2.drawImage(image, tran, null); break; case DRAW_MODE_HEIGHT: tran.scale(heightscale, heightscale); g2.drawImage(image, tran, null); break; default: tran.scale(widthscale, heightscale); g2.drawImage(image, tran, null); break; } } }
public static BufferedImage rotateImage(BufferedImage bi) { int w = bi.getWidth(); int h = bi.getHeight(); BufferedImage image = new BufferedImage(h, w, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.setPaint(Color.white); // getBackground()); g2.fillRect(0, 0, h, w); g2.rotate(90 * Math.PI / 180); g2.drawImage(bi, 0, -h, w, h, null); // this); g2.dispose(); return image; }
private BufferedImage convert(BufferedImage image, int imageType) { if (image.getType() == imageType) { return image; } int w = image.getWidth(); int h = image.getHeight(); BufferedImage newImg = new BufferedImage(w, h, imageType); ColorSpace srcSpace = image.getColorModel().getColorSpace(); ColorSpace newSpace = newImg.getColorModel().getColorSpace(); ColorConvertOp convert = new ColorConvertOp(srcSpace, newSpace, null); convert.filter(image, newImg); return newImg; }
Sidebar() { super(BoxLayout.Y_AXIS); try { back = ImageIO.read( ClassLoader.getSystemClassLoader() .getResource("org/madeirahs/editor/ui/help_sidebar.png")); scaleImage(); setPreferredSize(new Dimension(back.getWidth(), back.getHeight())); } catch (IOException e) { e.printStackTrace(); } }
/* * Method takes a parameter of a BufferedImage * and returns a 2d array */ public static int[][] readIntoArray(BufferedImage x) { int width = x.getWidth(); int height = x.getHeight(); // initialize the 2d array to the size of the picture int[][] imagePixels = new int[width][height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { imagePixels[i][j] = x.getRGB(i, j); // store RGB value in array // printPixelARGB(x.getRGB(i,j)); } } return imagePixels; }
private static BufferedImage applyKernelFilter(final BufferedImage source, Kernel customFilter) throws IOException, NullPointerException { if (verifyNotNull(source)) { RenderingHints requiredRenderingHintsForQuality = new RenderingHints( generateRenderingHintsBasedOnProperties(ImageProcessing.HIGH_BEST_SLOW)); ConvolveOp bufferedImageOperations = new ConvolveOp(customFilter, ConvolveOp.EDGE_NO_OP, requiredRenderingHintsForQuality); BufferedImage target = new BufferedImage(source.getWidth(), source.getHeight(), source.getType()); target = bufferedImageOperations.filter(source, target); if (verifyNotNull(target)) { return target; } throw new NullPointerException("Internal: Target was null"); } throw new NullPointerException(E_OBJECT_WAS_NULL); }
/** * Simple method to use if one wants to change the current color scheme to e.g grayscale, * black/white and so on * * @param source source image object * @param colorSpaceType color space type. see java.awt.color.ColorSpace.<TYPES> * @param <T> type * @return BufferedImage * @throws IOException _ * @throws NullPointerException _ */ public static <T> BufferedImage convertColorScheme(final T source, final Integer colorSpaceType) throws IOException, NullPointerException { if (verifyNotNull(source, colorSpaceType)) { BufferedImage sourceImage; sourceImage = convertToBufferedImage(source); BufferedImage target = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType()); if (verifyNotNull(sourceImage)) { ColorSpace colorSpace = ColorSpace.getInstance(colorSpaceType); ColorConvertOp converter = new ColorConvertOp(colorSpace, null); target = converter.filter(sourceImage, target); if (verifyNotNull(target)) { return target; } throw new NullPointerException("Unable to create target image. Result was null"); } } throw new NullPointerException(E_OBJECT_WAS_NULL); }
private void makeNoDataTransparent( BufferedImage image, short missingDataSignal, short missingDataReplacement) { WritableRaster raster = null; if (null != image && (image.getType() == BufferedImage.TYPE_4BYTE_ABGR || image.getType() == BufferedImage.TYPE_INT_ARGB) && null != (raster = image.getRaster())) { int nodata_r = missingDataSignal & 0xff; int nodata_g = missingDataSignal & 0xff; int nodata_b = missingDataSignal & 0xff; int[] pixel = new int[4]; int[] transparentPixel = new int[] { 0xFF & missingDataReplacement /* red */, 0xFF & missingDataReplacement /* green */, 0xFF & missingDataReplacement, 0x00 /* alpha */ }; int width = image.getWidth(); int height = image.getHeight(); for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { // We know, by the nature of this source, that we are dealing with RGBA rasters... raster.getPixel(i, j, pixel); if (pixel[0] == nodata_r && pixel[1] == nodata_g && pixel[2] == nodata_b) { // pixel[0] = pixel[1] = pixel[2] = 0xFF & // missingDataReplacement; // pixel[3] = 0; // transparent raster.setPixel(i, j, transparentPixel); } else { pixel[3] = 0xff; // non-transparent raster.setPixel(i, j, pixel); } } } } }
public ImageFont(String pathToImage, int numCols, int numRows) { try { tilesImg = convertToARGB(ImageIO.read(new File(pathToImage))); this.imgW = tilesImg.getWidth(); this.imgH = tilesImg.getHeight(); this.numCols = numCols; this.numRows = numRows; this.numTiles = numCols * numRows; this.tW = this.imgW / this.numCols; this.tH = this.imgH / this.numRows; this.tiles = new BufferedImage[this.numTiles]; for (int i = 0; i < numCols; i++) { for (int j = 0; j < numRows; j++) { tiles[(numCols * j) + i] = tilesImg.getSubimage(i * tW, j * tH, tW, tH); } } } catch (IOException e) { System.out.println("Couldn't load the image: " + e); } }
public CA toScaledCA(float scale) { int w = _i.getWidth(); int h = _i.getHeight(); /* BufferedImage scaled = new BufferedImage((int)(w*scale), (int)(h*scale), BufferedImage.TYPE_INT_ARGB); AffineTransform at = new AffineTransform(); at.scale(scale, scale); RenderingHints hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); AffineTransformOp scaleOp = new AffineTransformOp(at, hints); scaled = scaleOp.filter(_i, scaled); return new CA(scaled); */ return new CA( Scalr.resize( _i, Scalr.Method.ULTRA_QUALITY, (int) (w * scale), (int) (h * scale), Scalr.OP_ANTIALIAS, Scalr.OP_BRIGHTER)); }
// compare the two images in this object. public void compare() { // setup change display image imgc = imageToBufferedImage(img1); Graphics2D gc = imgc.createGraphics(); gc.setColor(Color.RED); // convert to gray images. img1 = imageToBufferedImage(GrayFilter.createDisabledImage(img1)); img2 = imageToBufferedImage(GrayFilter.createDisabledImage(img2)); // how big are each section int blocksx = (int) (img1.getWidth() / comparex); int blocksy = (int) (img1.getHeight() / comparey); // set to a match by default, if a change is found then flag non-match this.match = true; // loop through whole image and compare individual blocks of images for (int y = 0; y < comparey; y++) { if (debugMode > 0) System.out.print("|"); for (int x = 0; x < comparex; x++) { int b1 = getAverageBrightness( img1.getSubimage(x * blocksx, y * blocksy, blocksx - 1, blocksy - 1)); int b2 = getAverageBrightness( img2.getSubimage(x * blocksx, y * blocksy, blocksx - 1, blocksy - 1)); int diff = Math.abs(b1 - b2); if (diff > factorA) { // the difference in a certain region has passed the threshold value of // factorA // draw an indicator on the change image to show where change was detected. gc.drawRect(x * blocksx, y * blocksy, blocksx - 1, blocksy - 1); this.match = false; } if (debugMode == 1) System.out.print((diff > factorA ? "X" : " ")); if (debugMode == 2) System.out.print(diff + (x < comparex - 1 ? "," : "")); } if (debugMode > 0) System.out.println("|"); } }
public void insertBuilding(int i, int j, int index) { if (!tiles[i][j].getValue().equals("")) { JOptionPane.showMessageDialog(null, "There is already a building here"); return; } String temp = bb.get(index).getText(); String[] parts = temp.split("-"); int newQ = Integer.parseInt(parts[1]) - 1; if (newQ < 0) return; Building tB = bList.get(0); for (int b = 0; b < bList.size(); b++) { if (bList.get(b).getName().equals(parts[0])) { tB = bList.get(b); // System.out.println("here"); break; } } Image image = null; BufferedImage buffered; try { image = ImageIO.read(new File("images/" + tB.getName().replace(" ", "_") + ".png")); System.out.println("Loaded image"); } catch (IOException e) { System.out.println("Failed to load image"); } buffered = (BufferedImage) image; for (int c = 0; c < tB.getQWidth(); c++) { for (int r = 0; r < tB.getQHeight(); r++) { if (i + c == 40 || j + r == 40) { JOptionPane.showMessageDialog(null, "Placing a building here would be out of bounds"); return; } if (!tiles[i + c][j + r].getValue().equals("")) { JOptionPane.showMessageDialog(null, "Placing a building here will result to a overlap"); return; } } } double w = buffered.getWidth() / tB.getQWidth(); double h = buffered.getHeight() / tB.getQHeight(); for (int c = 0; c < tB.getQWidth(); c++) { for (int r = 0; r < tB.getQHeight(); r++) { tiles[i + c][j + r].setBackground(new Color(51, 204, 51)); tiles[i + c][j + r].setIcon( new ImageIcon( resize( buffered.getSubimage((int) w * r, (int) h * c, (int) w, (int) h), tiles[i + c][j + r].getWidth(), tiles[i + c][j + r].getHeight()))); String tValue = (c == 0 && r == 0) ? tB.getName() : i + "-" + j; // System.out.println(tValue); tiles[i + c][j + r].setValue(tValue); } } // tiles[i][j].setBackground(Color.BLUE); bb.get(index).setText(parts[0] + "-" + newQ); }
public BufferedImage composeImageForSector( Sector sector, int imageWidth, int imageHeight, int levelNumber, String mimeType, boolean abortOnError, BufferedImage image) { if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } if (levelNumber < 0) { levelNumber = this.levels.getLastLevel().getLevelNumber(); } else if (levelNumber > this.levels.getLastLevel().getLevelNumber()) { Logging.logger() .warning( Logging.getMessage( "generic.LevelRequestedGreaterThanMaxLevel", levelNumber, this.levels.getLastLevel().getLevelNumber())); levelNumber = this.levels.getLastLevel().getLevelNumber(); } MercatorTextureTile[][] tiles = this.getTilesInSector(sector, levelNumber); if (tiles.length == 0 || tiles[0].length == 0) { Logging.logger().severe(Logging.getMessage("layers.TiledImageLayer.NoImagesAvailable")); return null; } if (image == null) image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); for (MercatorTextureTile[] row : tiles) { for (MercatorTextureTile tile : row) { if (tile == null) continue; BufferedImage tileImage; try { tileImage = this.getImage(tile, mimeType); double sh = ((double) imageHeight / (double) tileImage.getHeight()) * (tile.getSector().getDeltaLat().divide(sector.getDeltaLat())); double sw = ((double) imageWidth / (double) tileImage.getWidth()) * (tile.getSector().getDeltaLon().divide(sector.getDeltaLon())); double dh = imageHeight * (-tile.getSector().getMaxLatitude().subtract(sector.getMaxLatitude()).degrees / sector.getDeltaLat().degrees); double dw = imageWidth * (tile.getSector().getMinLongitude().subtract(sector.getMinLongitude()).degrees / sector.getDeltaLon().degrees); AffineTransform txf = g.getTransform(); g.translate(dw, dh); g.scale(sw, sh); g.drawImage(tileImage, 0, 0, null); g.setTransform(txf); } catch (Exception e) { if (abortOnError) throw new RuntimeException(e); String message = Logging.getMessage("generic.ExceptionWhileRequestingImage", tile.getPath()); Logging.logger().log(java.util.logging.Level.WARNING, message, e); } } } return image; }