/** * Sets the zoom level used to display the image, and the zooming center, around which zooming is * done. * * <p>This method is used in programmatic zooming. After a new zoom level is set the image is * repainted. * * @param newZoom the zoom level used to display this panel's image. */ public void setZoom(double newZoom, Point zoomingCenter) { Coords imageP = panelToImageCoords(zoomingCenter); if (imageP.x < 0.0) { imageP.x = 0.0; } if (imageP.y < 0.0) { imageP.y = 0.0; } if (imageP.x >= image.getWidth()) { imageP.x = image.getWidth() - 1.0; } if (imageP.y >= image.getHeight()) { imageP.y = image.getHeight() - 1.0; } Coords correctedP = imageToPanelCoords(imageP); double oldZoom = getZoom(); scale = zoomToScale(newZoom); Coords panelP = imageToPanelCoords(imageP); originX += (correctedP.getIntX() - (int) panelP.x); originY += (correctedP.getIntY() - (int) panelP.y); firePropertyChange(ZOOM_LEVEL_CHANGED_PROPERTY, new Double(oldZoom), new Double(getZoom())); repaint(); }
public static BufferedImage doFilter(BufferedImage img) { BufferedImage img2 = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_3BYTE_BGR); // img.getSubimage(0, 0, img.getWidth(), img.getHeight()); for (int i = 0; i < img2.getWidth(); i++) { for (int j = 0; j < img2.getHeight(); j++) { img2.setRGB(i, j, img.getRGB(i, j)); // img2.setRGB(i, j, Color.BLACK.getRGB()); } } int a = 32; for (int j = 0; j < img2.getHeight(); j++) { for (int i = 0; i < img2.getWidth(); i++) { int c = img.getRGB(i, j); Color c2 = new Color(c); Error er = new Error(); er.r = (int) (a * matrix[i % 2][j % 2]); er.g = er.r; er.b = er.r; c2 = addToPixel(c2, er, 1); Color c3 = getClosestPixel(c2); setPixel(img2, i, j, c3); // oldpixel := pixel[x][y] + threshold_map_4x4[x mod 4][y mod 4] // newpixel := find_closest_palette_color(oldpixel) // pixel[x][y] := newpixel } } return img2; }
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); }
private int drawPreviewImagePortion( List<Map<String, BufferedImage>> generatedImages, Graphics2D graphics, String key, int drawPosition, int previewImageHeight, int verticalOffset) { final Map<String, BufferedImage> firstFloorImages = generatedImages.get(0); final BufferedImage firstFloorImage = firstFloorImages.get(key); final int verticalPosition = ((previewImageHeight - firstFloorImage.getHeight()) / 2) + verticalOffset; graphics.drawImage(firstFloorImage, drawPosition, verticalPosition, null); int outputWidth = firstFloorImage.getWidth(); for (int i = 1; i < generatedImages.size(); i++) { final BufferedImage storyImage = generatedImages.get(i).get(key); graphics.drawImage( storyImage, drawPosition, verticalPosition - (storyImage.getHeight() - firstFloorImage.getHeight()), null); } return outputWidth; }
/** * 将照片logo添加到二维码中间 * * @param image 生成的二维码照片对象 * @param imagePath 照片保存路径 * @param logoPath logo照片路径 * @param formate 照片格式 */ public static void overlapImage( BufferedImage image, String formate, String imagePath, String logoPath, MatrixToLogoImageConfig logoConfig) { try { BufferedImage logo = ImageIO.read(new File(logoPath)); Graphics2D g = image.createGraphics(); // 考虑到logo照片贴到二维码中,建议大小不要超过二维码的1/5; int width = image.getWidth() / logoConfig.getLogoPart(); int height = image.getHeight() / logoConfig.getLogoPart(); // logo起始位置,此目的是为logo居中显示 int x = (image.getWidth() - width) / 2; int y = (image.getHeight() - height) / 2; // 绘制图 g.drawImage(logo, x, y, width, height, null); // 给logo画边框 // 构造一个具有指定线条宽度以及 cap 和 join 风格的默认值的实心 BasicStroke g.setStroke(new BasicStroke(logoConfig.getBorder())); g.setColor(logoConfig.getBorderColor()); g.drawRect(x, y, width, height); g.dispose(); // 写入logo照片到二维码 ImageIO.write(image, formate, new File(imagePath)); } catch (Exception e) { e.printStackTrace(); } }
private BufferedImage windowMonochrome( ImageListViewCell displayedCell, BufferedImage srcImg, float windowLocation, float windowWidth) { BufferedImage destImg = new BufferedImage(srcImg.getWidth(), srcImg.getHeight(), BufferedImage.TYPE_INT_RGB); boolean isSigned = false; int minValue = 0; { // hack: try to determine signedness and minValue from DICOM metadata if available -- // the BufferedImage's metadata don't contain that information reliably. // Only works for some special cases ImageListViewModelElement elt = displayedCell.getDisplayedModelElement(); if (elt instanceof DicomImageListViewModelElement) { DicomImageListViewModelElement delt = (DicomImageListViewModelElement) elt; DicomObject imgMetadata = delt.getDicomImageMetaData(); int bitsAllocated = imgMetadata.getInt(Tag.BitsAllocated); isSigned = (1 == imgMetadata.getInt(Tag.PixelRepresentation)); if (isSigned && (bitsAllocated > 0)) { minValue = -(1 << (bitsAllocated - 1)); } } } final int windowedImageGrayscalesCount = 256; // for BufferedImage.TYPE_INT_RGB float scale = windowedImageGrayscalesCount / windowWidth; float offset = (windowWidth / 2 - windowLocation) * scale; if (!(srcImg.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_GRAY)) { throw new IllegalArgumentException("source image must be grayscales"); } Raster srcRaster = srcImg.getRaster(); if (srcRaster.getNumBands() != 1) { throw new IllegalArgumentException( "grayscale source image must have one color band, but has " + srcRaster.getNumBands() + "??"); } WritableRaster resultRaster = destImg.getRaster(); for (int x = 0; x < srcImg.getWidth(); x++) { for (int y = 0; y < srcImg.getHeight(); y++) { int srcGrayValue = srcRaster.getSample(x, y, 0); if (isSigned) { srcGrayValue = (int) (short) srcGrayValue; // will only work for 16-bit signed... } float destGrayValue = scale * srcGrayValue + offset; // clamp if (destGrayValue < 0) { destGrayValue = 0; } else if (destGrayValue >= windowedImageGrayscalesCount) { destGrayValue = windowedImageGrayscalesCount - 1; } resultRaster.setSample(x, y, 0, destGrayValue); resultRaster.setSample(x, y, 1, destGrayValue); resultRaster.setSample(x, y, 2, destGrayValue); } } return destImg; }
public void loadWorldFromImage(String filepath) { try { BufferedImage image = ImageIO.read(World.class.getResourceAsStream(filepath)); width = image.getWidth(); height = image.getHeight(); data.clear(); for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { int rgb = image.getRGB(x, y); int red = (rgb >> 16) & 0x000000FF; int green = (rgb >> 8) & 0x000000FF; int blue = (rgb >> 0) & 0x000000FF; String colour = red + "-" + green + "-" + blue; switch (colour) { case "0-102-0": data.add(0); break; case "102-102-102": data.add(1); break; } } } } catch (IOException e) { e.printStackTrace(); } }
/** * 画像のリサイズ * * @param srcImage 元画像 * @param destWidth 横幅 * @param destHeight 高さ * @return */ public BufferedImage rescaleImage(BufferedImage srcImage, int dstWidth, int dstHeight) { BufferedImage dstImage = null; if (srcImage.getColorModel() instanceof IndexColorModel) { dstImage = new BufferedImage( dstWidth, dstHeight, srcImage.getType(), (IndexColorModel) srcImage.getColorModel()); } else { if (srcImage.getType() == 0) { dstImage = new BufferedImage(dstWidth, dstHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); } else { dstImage = new BufferedImage(dstWidth, dstHeight, srcImage.getType()); } } double x = (double) dstWidth / srcImage.getWidth(); double y = (double) dstHeight / srcImage.getHeight(); AffineTransform af = AffineTransform.getScaleInstance(x, y); if (dstImage.getColorModel().hasAlpha() && dstImage.getColorModel() instanceof IndexColorModel) { int pixel = ((IndexColorModel) dstImage.getColorModel()).getTransparentPixel(); for (int i = 0; i < dstImage.getWidth(); ++i) { for (int j = 0; j < dstImage.getHeight(); ++j) { dstImage.setRGB(i, j, pixel); } } } Graphics2D g2 = (Graphics2D) dstImage.createGraphics(); g2.drawImage(srcImage, af, null); g2.dispose(); return dstImage; }
public static Icon getFixedBoundIcon(String filePath, int height, int width) throws Exception { double Ratio = 0.0; // 缩放比例 File F = new File(filePath); if (!F.isFile()) throw new Exception(F + " is not image file error in getFixedBoundIcon! "); Icon ret = new ImageIcon(filePath); BufferedImage Bi = ImageIO.read(F); if ((Bi.getHeight() > height) || (Bi.getWidth() > width)) { if (Bi.getHeight() > Bi.getWidth()) { Ratio = (new Integer(height)).doubleValue() / Bi.getHeight(); } else { Ratio = (new Integer(width)).doubleValue() / Bi.getWidth(); } int lastLength = filePath.lastIndexOf(" . "); String subFilePath = filePath.substring(0, lastLength); String fileType = filePath.substring(lastLength); File zoomFile = new File(subFilePath + " _ " + height + " _ " + width + fileType); Image Itemp = Bi.getScaledInstance(width, height, Bi.SCALE_SMOOTH); AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(Ratio, Ratio), null); Itemp = op.filter(Bi, null); try { ImageIO.write((BufferedImage) Itemp, " jpg ", zoomFile); ret = new ImageIcon(zoomFile.getPath()); } catch (Exception ex) { System.out.println(" ######## here error : " + ex); } } return ret; }
@Override public List<Frame> execute(CVParticle particle) throws Exception { List<Frame> result = new ArrayList<Frame>(); if (!(particle instanceof Frame)) return result; Frame frame = (Frame) particle; BufferedImage image = frame.getImage(); if (image == null) return result; if (image.getWidth() < 2 * cols || image.getHeight() < 2 * rows) return result; int width = image.getWidth() / cols; int height = image.getHeight() / rows; int tileIndex = 0; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { Rectangle box = new Rectangle(c * width, r * height, width + pixelOverlap, height + pixelOverlap); box = box.intersection(frame.getBoundingBox()); BufferedImage tile = image.getSubimage(box.x, box.y, box.width, box.height); byte[] buffer = ImageUtils.imageToBytes(tile, imageType); result.add( new Frame( frame.getStreamId() + "_" + tileIndex, frame.getSequenceNr(), imageType, buffer, frame.getTimestamp(), box)); tileIndex++; } } return result; }
public static BufferedImage rotateImage(BufferedImage image, double theta) { int degrees = (int) Math.abs(Math.toDegrees(theta)); double xCenter = image.getWidth() / 2; double yCenter = image.getHeight() / 2; AffineTransform rotateTransform = AffineTransform.getRotateInstance(-theta, xCenter, yCenter); // Translation adjustments so image still centered after rotate width/height changes if (image.getHeight() != image.getWidth() && degrees != 180 && degrees != 0) { Point2D origin = new Point2D.Double(0.0, 0.0); origin = rotateTransform.transform(origin, null); double yTranslate = origin.getY(); Point2D yMax = new Point2D.Double(0, image.getHeight()); yMax = rotateTransform.transform(yMax, null); double xTranslate = yMax.getX(); AffineTransform translationAdjustment = AffineTransform.getTranslateInstance(-xTranslate, -yTranslate); rotateTransform.preConcatenate(translationAdjustment); } AffineTransformOp op = new AffineTransformOp(rotateTransform, AffineTransformOp.TYPE_BILINEAR); // Have to recopy image because of JDK bug #4723021, AffineTransformationOp throwing exception // sometimes image = copyImage(image, BufferedImage.TYPE_INT_ARGB); // Need to create filter dest image ourselves since AffineTransformOp's own dest image creation // throws exceptions in some cases. Rectangle bounds = op.getBounds2D(image).getBounds(); BufferedImage finalImage = new BufferedImage( (int) bounds.getWidth(), (int) bounds.getHeight(), BufferedImage.TYPE_INT_ARGB); return op.filter(image, finalImage); }
public static void scalePictureToMax( InputStream in, OutputStream out, int maxWidth, int maxHeight) throws Exception { BufferedImage bsrc = ImageIO.read(in); int height = 0; int width = 0; double aspectRatio = ((double) bsrc.getHeight()) / ((double) bsrc.getWidth()); double maxAR = ((double) maxHeight) / ((double) maxWidth); if (aspectRatio > maxAR) { height = maxHeight; width = (int) Math.round(maxHeight / aspectRatio); } else { width = maxWidth; height = (int) Math.round(maxWidth * aspectRatio); } BufferedImage bdest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = bdest.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance( (double) width / bsrc.getWidth(), (double) height / bsrc.getHeight()); g.drawRenderedImage(bsrc, at); ImageIO.write(bdest, "PNG", out); }
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 BufferedImage getImageSummary(VillainCard h) { int maxWidth = 24; int maxHeight = 24; BufferedImage bi = new BufferedImage(maxWidth * (3), maxHeight, BufferedImage.TYPE_INT_ARGB); Graphics g2 = bi.getGraphics(); int offset = 0; BufferedImage icon = getCardIcon(h.cardTeam, maxWidth, maxHeight); g2.drawImage( icon, offset + ((maxWidth / 2) - (icon.getWidth() / 2)), ((maxHeight / 2) - (icon.getHeight() / 2)), null); offset += maxWidth; icon = getCardIcon(h.cardPower, maxWidth, maxHeight); g2.drawImage( icon, offset + ((maxWidth / 2) - (icon.getWidth() / 2)), ((maxHeight / 2) - (icon.getHeight() / 2)), null); g2.dispose(); return bi; }
@Override protected void paintComponent(Graphics graphics) { // Fill in the background: Graphics2D g = (Graphics2D) graphics; Shape clip = g.getClip(); g.setColor(LightZoneSkin.Colors.NeutralGray); g.fill(clip); if (preview == null) { PlanarImage image = currentImage.get(); if (image == null) { engine.update(null, false); } else if (visibleRect != null && getHeight() > 1 && getWidth() > 1) { preview = cropScaleGrayscale(visibleRect, image); } } if (preview != null) { int dx, dy; AffineTransform transform = new AffineTransform(); if (getSize().width > preview.getWidth()) dx = (getSize().width - preview.getWidth()) / 2; else dx = 0; if (getSize().height > preview.getHeight()) dy = (getSize().height - preview.getHeight()) / 2; else dy = 0; transform.setToTranslation(dx, dy); try { g.drawRenderedImage(preview, transform); } catch (Exception e) { e.printStackTrace(); } } }
public RigidBodyTransform detect(BufferedImage image) { if (intrinsicParameters == null) setDefaultIntrinsicParameter(image.getHeight(), image.getWidth(), Math.PI / 4); ImageFloat32 gray = new ImageFloat32(image.getWidth(), image.getHeight()); ConvertBufferedImage.convertFrom(image, gray); detector.setIntrinsic(intrinsicParameters); detector.detect(gray); // display the results if (detector.totalFound() == 0) { return null; } else { int closestIndex = -1; double closestDistance = Double.MAX_VALUE; Se3_F64 targetToSensor = new Se3_F64(); for (int i = 0; i < detector.totalFound(); i++) { detector.getFiducialToCamera(i, targetToSensor); double dist = targetToSensor.getT().norm(); if (dist < closestDistance) { closestIndex = i; closestDistance = dist; } } detector.getFiducialToCamera(closestIndex, targetToSensor); Vector3D_F64 translation = targetToSensor.getT(); Matrix3d rotation = new Matrix3d(targetToSensor.getR().data); RigidBodyTransform transform = new RigidBodyTransform( rotation, new Vector3d(translation.x, translation.y, translation.z)); return transform; } }
public void extract(BufferedImage image) { histogram = new double[18]; double[] directionality; ColorConvertOp op = new ColorConvertOp( image.getColorModel().getColorSpace(), ColorSpace.getInstance(ColorSpace.CS_GRAY), new RenderingHints( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY)); BufferedImage bimg = op.filter(image, null); bimg = ImageUtils.scaleImage(bimg, MAX_IMG_HEIGHT); Raster raster = bimg.getRaster(); int[] tmp = new int[3]; this.grayScales = new int[raster.getWidth()][raster.getHeight()]; for (int i = 0; i < raster.getWidth(); i++) { for (int j = 0; j < raster.getHeight(); j++) { raster.getPixel(i, j, tmp); this.grayScales[i][j] = tmp[0]; } } imgWidth = bimg.getWidth(); imgHeight = bimg.getHeight(); histogram[0] = this.coarseness(bimg.getWidth(), bimg.getHeight()); histogram[1] = this.contrast(); directionality = this.directionality(); for (int i = 2; i < histogram.length; i++) { histogram[i] = directionality[i - 2]; } }
private void pickHeliImage() { String image = null; if (this.getXSpeed() > 0) image = "heli_right"; else if (this.getXSpeed() < 0) image = "heli_left"; String lastImage = this.helicopter.getCurrentImageName(); if (image == null) if (lastImage.equals("heli_left") || lastImage.equals("heli_still_left")) image = "heli_still_left"; else image = "heli_still_right"; if (!image.equals(lastImage)) { if (lastImage.equals("heli_still_left") || lastImage.equals("heli_still_right") || image.equals("heli_still_right") || image.equals("heli_still_left")) { BufferedImage before = this.helicopter.getImageGroupHolder().getImage(lastImage); BufferedImage after = this.helicopter.getImageGroupHolder().getImage(image); this.moveBy( (before.getWidth() - after.getWidth()) / 2, (before.getHeight() - after.getHeight()) / 2); } this.helicopter.setCurrentImage(image); this.clearHitboxes(); this.addHitboxes(HeliSprite.hitboxes.get(image)); } }
private BufferedImage windowRGB(BufferedImage srcImg, float windowLocation, float windowWidth) { BufferedImage destImg = new BufferedImage(srcImg.getWidth(), srcImg.getHeight(), BufferedImage.TYPE_INT_RGB); final int windowedImageBandValuesCount = 256; // for BufferedImage.TYPE_INT_RGB float scale = windowedImageBandValuesCount / windowWidth; float offset = (windowWidth / 2 - windowLocation) * scale; if (!srcImg.getColorModel().getColorSpace().isCS_sRGB()) { throw new IllegalArgumentException("source image must be RGB"); } Raster srcRaster = srcImg.getRaster(); if (srcRaster.getNumBands() != 3) { throw new IllegalArgumentException( "RGB source image must have three color bands, but has " + srcRaster.getNumBands() + "??"); } WritableRaster resultRaster = destImg.getRaster(); for (int x = 0; x < srcImg.getWidth(); x++) { for (int y = 0; y < srcImg.getHeight(); y++) { for (int band = 0; band < 3; band++) { int srcGrayValue = srcRaster.getSample(x, y, band); float destGrayValue = scale * srcGrayValue + offset; // clamp if (destGrayValue < 0) { destGrayValue = 0; } else if (destGrayValue >= windowedImageBandValuesCount) { destGrayValue = windowedImageBandValuesCount - 1; } resultRaster.setSample(x, y, band, destGrayValue); } } } return destImg; }
public static Image getScaledInstance(File file) throws Exception { srcBImage = javax.imageio.ImageIO.read(file); if (srcBImage.getWidth() > srcBImage.getHeight()) { width = 100; height = (srcBImage.getHeight() * 100) / srcBImage.getWidth(); } else { height = 100; width = (srcBImage.getWidth() * 100) / srcBImage.getHeight(); } dest = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); dest2 = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); g = dest.getGraphics(); g.setColor(Color.white); g.fillRect(0, 0, 100, 100); g.drawImage(srcBImage, 0, 0, width, height, null); g.dispose(); srcBImage = null; blurOperator.filter(dest, dest2); return dest2; }
// TODO currently allows for collisions if same name & different filetype public void loadImage(String path) { BufferedImage readImage = null; try { readImage = ImageIO.read(new File("images/" + path)); } catch (IOException e) { e.printStackTrace(); } if (readImage != null) { BufferedImage aImages[] = new BufferedImage[8]; BufferedImage image = new BufferedImage( readImage.getWidth(), readImage.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics g = image.getGraphics(); g.drawImage(readImage, 0, 0, null); for (int i = 0; i < 8; i++) { AffineTransform trans = new AffineTransform(); trans.translate(image.getWidth() / 2, image.getHeight() / 2); trans.rotate(Math.PI * i / 4.0); trans.translate(-image.getWidth() / 2, -image.getHeight() / 2); AffineTransformOp op = new AffineTransformOp(trans, AffineTransformOp.TYPE_BILINEAR); aImages[i] = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); op.filter(image, aImages[i]); } images.add( new Asset( path.substring(0, path.length() - 4), aImages)); // assumes standard 3 letter postfix } }
public void drawPixelatedImage(BufferedImage img, int locationX, int locationY) { if (isDrawingPixelatedImages()) { BufferedImage bi = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D) bi.getGraphics(); g2.setColor(Color.WHITE); g2.fillRect(0, 0, img.getWidth(), img.getHeight()); g2.drawImage(img, 0, 0, observer); g2.dispose(); for (int x = 0; x < bi.getWidth(observer); x++) { for (int y = 0; y < bi.getHeight(observer); y++) { int rgb = bi.getRGB(x, y); gc.setColor(new Color(rgb)); gc.setStroke(new BasicStroke(1.0f)); gc.drawLine( locationX + xOffset + x, locationY + yOffset + y, locationX + xOffset + x, locationY + yOffset + y); // gc.drawLine(locationX+xOffset+x, locationY+yOffset+y, // locationX+xOffset+x+1, locationY+yOffset+y); // gc.drawLine(locationX+xOffset+x, locationY+yOffset+y+1, // locationX+xOffset+x+1, locationY+yOffset+y+1); // gc.fillRect(locationX+xOffset+x, locationY+yOffset+y, 1, 1); } } } else { while (!gc.drawImage(img, locationX, locationY, observer)) ; } }
public static void main(String[] args) { try { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); File input = new File("traffic_signal.jpg"); BufferedImage image = ImageIO.read(input); byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3); mat.put(0, 0, data); Mat mat1 = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC1); Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2GRAY); byte[] data1 = new byte[mat1.rows() * mat1.cols() * (int) (mat1.elemSize())]; mat1.get(0, 0, data1); BufferedImage image1 = new BufferedImage(mat1.cols(), mat1.rows(), BufferedImage.TYPE_BYTE_GRAY); image1.getRaster().setDataElements(0, 0, mat1.cols(), mat1.rows(), data1); File ouptut = new File("output\\grayscale_" + new Date().getTime() + ".jpg"); ImageIO.write(image1, "jpg", ouptut); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } }
/** * Verifies that the specified images match. * * @param expected the expected image to check against * @param actual the actual image */ private static void assertEqual(BufferedImage expected, BufferedImage actual) { int w = expected.getWidth(); int h = expected.getHeight(); Assert.assertEquals("width", w, actual.getWidth()); Assert.assertEquals("height", h, actual.getHeight()); int[] expectedPixels = new int[w * h]; expected.getRGB(0, 0, w, h, expectedPixels, 0, w); int[] actualPixels = new int[w * h]; actual.getRGB(0, 0, w, h, actualPixels, 0, w); for (int i = 0; i < expectedPixels.length; i++) { int expectedPixel = expectedPixels[i]; int actualPixel = actualPixels[i]; if (expectedPixel != actualPixel) { int x = i % w; int y = i / w; throw new ComparisonFailure( "pixel at " + x + ", " + y, toHexString(expectedPixel), toHexString(actualPixel)); } } }
private BufferedImage aplicaFiltroMatrizConvolucion( double[][] filter, double factor, double bias, BufferedImage img) { imgTmp = new BufferedImage(img.getWidth(), img.getHeight(), img.getType()); for (int x = 0; x < img.getWidth(); x++) { for (int y = 0; y < img.getHeight(); y++) { int r = 0, g = 0, b = 0; for (int filterX = 0; filterX < filter.length; filterX++) for (int filterY = 0; filterY < filter.length; filterY++) { int imageX = (x - filter.length / 2 + filterX + img.getWidth()) % img.getWidth(); int imageY = (y - filter.length / 2 + filterY + img.getHeight()) % img.getHeight(); Color c = new Color(img.getRGB(imageX, imageY)); r += c.getRed() * filter[filterX][filterY]; g += c.getGreen() * filter[filterX][filterY]; b += c.getBlue() * filter[filterX][filterY]; } imgTmp.setRGB( x, y, new Color( Math.min(Math.max((int) (factor * r + bias), 0), 255), Math.min(Math.max((int) (factor * g + bias), 0), 255), Math.min(Math.max((int) (factor * b + bias), 0), 255)) .getRGB()); } } return imgTmp; }
/* * create QR code with overlay */ public static void createQRCode( String qrCodeData, String outputFilePath, String overlayFilePath, String charset, Map<EncodeHintType, ErrorCorrectionLevel> hintMap, int qrCodeheight, int qrCodewidth) throws WriterException, IOException { // create QR code <BufferedImage> QRCodeWriter qrWriter = new QRCodeWriter(); BitMatrix matrix = qrWriter.encode(qrCodeData, BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap); BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix); // read overlay image BufferedImage overlay = ImageIO.read(new File(overlayFilePath)); // Draw the new image int deltaHeight = image.getHeight() - overlay.getHeight(); int deltaWidth = image.getWidth() - overlay.getWidth(); BufferedImage combined = new BufferedImage(qrCodeheight, qrCodewidth, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) combined.getGraphics(); g.drawImage(image, 0, 0, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); g.drawImage(overlay, (int) Math.round(deltaWidth / 2), (int) Math.round(deltaHeight / 2), null); ImageIO.write(combined, "PNG", new File(outputFilePath)); }
/** * 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); }
public void process(BufferedImage input) { setInputImage(input); image.reshape(input.getWidth(), input.getHeight()); transform.reshape(input.getWidth(), input.getHeight()); magnitude.reshape(input.getWidth(), input.getHeight()); phase.reshape(input.getWidth(), input.getHeight()); ConvertBufferedImage.convertFrom(input, image, true); fft.forward(image, transform); GDiscreteFourierTransformOps.shiftZeroFrequency(transform, true); GDiscreteFourierTransformOps.magnitude(transform, magnitude); GDiscreteFourierTransformOps.phase(transform, phase); // Convert it to a log scale for visibility GPixelMath.log(magnitude, magnitude); SwingUtilities.invokeLater( new Runnable() { public void run() { setPreferredSize(new Dimension(image.width + 50, image.height + 20)); processedImage = true; } }); doRefreshAll(); }
public BufferedImage filter(BufferedImage i) { BufferedImage result = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_RGB); // For each pixel in the image . . . for (int y = 0; y < i.getHeight(); y++) for (int x = 0; x < i.getWidth(); x++) { int pixel = i.getRGB(x, y); // Decompose the pixel in the amounts of red, green, and blue. int redAmount = (pixel >> 16) & 0xff; int greenAmount = (pixel >> 8) & 0xff; int blueAmount = pixel & 0xff; // Build a new pixel with the red and blue the same as the original, // but all green components set to the max value of 255. greenAmount = 255; // Compose the new pixel. int newPixel = (redAmount << 16) | (greenAmount << 8) | blueAmount; // Set the pixel of the new image. result.setRGB(x, y, newPixel); } return result; }
/** * Constructor de clase. * * @param f */ public ImageHSV(BufferedImage f) { H = new Matriz2D<Integer>(f.getWidth(), f.getHeight()); S = new Matriz2D<Integer>(f.getWidth(), f.getHeight()); V = new Matriz2D<Integer>(f.getWidth(), f.getHeight()); generateHSV(f); // Genero las 3 matrices en simultaneo }