List of usage examples for java.awt.image AffineTransformOp filter
public final WritableRaster filter(Raster src, WritableRaster dst)
From source file:AffineTransformApp.java
public void applyFilter() { AffineTransformOp op = new AffineTransformOp(transform, null); Graphics2D biDestG2D = biDest.createGraphics(); biDestG2D.clearRect(0, 0, biDest.getWidth(this), biDest.getHeight(this)); op.filter(biSrc, biDest); bi = biDest;/*w w w. jav a2 s . c om*/ }
From source file:org.apache.hadoop.chukwa.hicc.ImageSlicer.java
public BufferedImage prepare(String filename) { try {// w w w. j av a2s.co m src = ImageIO.read(new File(filename)); } catch (IOException e) { log.error("Image file does not exist:" + filename + ", can not render image."); } XYData fullSize = new XYData(1, 1); while (fullSize.getX() < src.getWidth() || fullSize.getY() < src.getHeight()) { fullSize.set(fullSize.getX() * 2, fullSize.getY() * 2); } float scaleX = (float) fullSize.getX() / src.getWidth(); float scaleY = (float) fullSize.getY() / src.getHeight(); log.info("Image size: (" + src.getWidth() + "," + src.getHeight() + ")"); log.info("Scale size: (" + scaleX + "," + scaleY + ")"); AffineTransform at = AffineTransform.getScaleInstance(scaleX, scaleY); // AffineTransform.getScaleInstance((fullSize.getX()-src.getWidth())/2,(fullSize.getY()-src.getHeight())/2); AffineTransformOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); BufferedImage dest = op.filter(src, null); return dest; }
From source file:org.apache.hadoop.chukwa.hicc.ImageSlicer.java
public BufferedImage tile(BufferedImage image, int level, XYData quadrant, XYData size, boolean efficient) throws Exception { double scale = Math.pow(2, level); if (efficient) { /* efficient: crop out the area of interest first, then scale and copy it */ XYData inverSize = new XYData((int) (image.getWidth(null) / (size.getX() * scale)), (int) (image.getHeight(null) / (size.getY() * scale))); XYData topLeft = new XYData(quadrant.getX() * size.getX() * inverSize.getX(), quadrant.getY() * size.getY() * inverSize.getY()); XYData newSize = new XYData((size.getX() * inverSize.getX()), (size.getY() * inverSize.getY())); if (inverSize.getX() < 1.0 || inverSize.getY() < 1.0) { throw new Exception("Requested zoom level (" + level + ") is too high."); }//from ww w . j a va 2s . c o m image = image.getSubimage(topLeft.getX(), topLeft.getY(), newSize.getX(), newSize.getY()); BufferedImage zoomed = new BufferedImage(size.getX(), size.getY(), BufferedImage.TYPE_INT_RGB); zoomed.getGraphics().drawImage(image, 0, 0, size.getX(), size.getY(), null); if (level > maxLevel) { maxLevel = level; } return zoomed; } else { /* inefficient: copy the whole image, scale it and then crop out the area of interest */ XYData newSize = new XYData((int) (size.getX() * scale), (int) (size.getY() * scale)); XYData topLeft = new XYData(quadrant.getX() * size.getX(), quadrant.getY() * size.getY()); if (newSize.getX() > image.getWidth(null) || newSize.getY() > image.getHeight(null)) { throw new Exception("Requested zoom level (" + level + ") is too high."); } AffineTransform tx = new AffineTransform(); AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); tx.scale(scale, scale); image = op.filter(image, null); BufferedImage zoomed = image.getSubimage(topLeft.getX(), topLeft.getY(), newSize.getX(), newSize.getY()); if (level > maxLevel) { maxLevel = level; } return zoomed; } }
From source file:org.alfresco.extension.countersign.action.executer.PDFSignatureProviderActionExecuter.java
/** * Scales the signature image to fit the provided signature field dimensions, * preserving the aspect ratio//from www. ja v a 2s. c om * * @param signatureImage * @param width * @param height * @return */ private BufferedImage scaleSignature(BufferedImage signatureImage, int width, int height) { if (signatureImage.getHeight() > height) { BufferedImage scaled = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); AffineTransform at = new AffineTransform(); at.scale(2.0, 2.0); AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); scaled = scaleOp.filter(signatureImage, scaled); return scaled; } else { return signatureImage; } }
From source file:org.geolatte.maprenderer.sld.graphics.ExternalGraphicsRepository.java
private BufferedImage scale(BufferedImage unscaledImage, float size) { Dimension dim = getWidthAndHeight(unscaledImage.getWidth(), unscaledImage.getHeight(), size); AffineTransform tx = new AffineTransform(); tx.scale(((double) dim.width / unscaledImage.getWidth()), ((double) dim.height) / unscaledImage.getHeight()); AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BICUBIC); return op.filter(unscaledImage, null); }
From source file:org.geolatte.maprenderer.sld.graphics.ExternalGraphicsRepository.java
private BufferedImage rotate(BufferedImage img, float rotation) { AffineTransform tx = new AffineTransform(); //determine center point of image int sx = img.getMinX() + img.getWidth() / 2; int sy = img.getMinY() + img.getHeight() / 2; double theta = Math.toRadians(rotation); tx.rotate(theta, sx, sy);// w w w . j a v a 2 s . co m AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); return op.filter(img, null); }
From source file:edu.umn.cs.spatialHadoop.operations.GeometricPlot.java
private static <S extends Shape> void plotLocal(Path inFile, Path outFile, OperationsParams params) throws IOException { int width = params.getInt("width", 1000); int height = params.getInt("height", 1000); Color strokeColor = params.getColor("color", Color.BLACK); int color = strokeColor.getRGB(); String hdfDataset = (String) params.get("dataset"); Shape shape = hdfDataset != null ? new NASARectangle() : (Shape) params.getShape("shape", null); Shape plotRange = params.getShape("rect", null); boolean keepAspectRatio = params.is("keep-ratio", true); String valueRangeStr = (String) params.get("valuerange"); MinMax valueRange;/*from w w w. j a v a 2s . c om*/ if (valueRangeStr == null) { valueRange = null; } else { String[] parts = valueRangeStr.split(","); valueRange = new MinMax(Integer.parseInt(parts[0]), Integer.parseInt(parts[1])); } InputSplit[] splits; FileSystem inFs = inFile.getFileSystem(params); FileStatus inFStatus = inFs.getFileStatus(inFile); if (inFStatus != null && !inFStatus.isDir()) { // One file, retrieve it immediately. // This is useful if the input is a hidden file which is automatically // skipped by FileInputFormat. We need to plot a hidden file for the case // of plotting partition boundaries of a spatial index splits = new InputSplit[] { new FileSplit(inFile, 0, inFStatus.getLen(), new String[0]) }; } else { JobConf job = new JobConf(params); ShapeInputFormat<Shape> inputFormat = new ShapeInputFormat<Shape>(); ShapeInputFormat.addInputPath(job, inFile); splits = inputFormat.getSplits(job, 1); } boolean vflip = params.is("vflip"); Rectangle fileMbr; if (plotRange != null) { fileMbr = plotRange.getMBR(); } else if (hdfDataset != null) { // Plotting a NASA file fileMbr = new Rectangle(-180, -90, 180, 90); } else { fileMbr = FileMBR.fileMBR(inFile, params); } if (keepAspectRatio) { // Adjust width and height to maintain aspect ratio if (fileMbr.getWidth() / fileMbr.getHeight() > (double) width / height) { // Fix width and change height height = (int) (fileMbr.getHeight() * width / fileMbr.getWidth()); } else { width = (int) (fileMbr.getWidth() * height / fileMbr.getHeight()); } } boolean adaptiveSample = shape instanceof Point && params.getBoolean("sample", false); float adaptiveSampleRatio = 0.0f; if (adaptiveSample) { // Calculate the sample ratio long recordCount = FileMBR.fileMBR(inFile, params).recordCount; adaptiveSampleRatio = params.getFloat(AdaptiveSampleFactor, 1.0f) * width * height / recordCount; } boolean gradualFade = !(shape instanceof Point) && params.getBoolean("fade", false); if (hdfDataset != null) { // Collects some stats about the HDF file if (valueRange == null) valueRange = Aggregate.aggregate(new Path[] { inFile }, params); NASAPoint.minValue = valueRange.minValue; NASAPoint.maxValue = valueRange.maxValue; NASAPoint.setColor1(params.getColor("color1", Color.BLUE)); NASAPoint.setColor2(params.getColor("color2", Color.RED)); NASAPoint.gradientType = params.getGradientType("gradient", NASAPoint.GradientType.GT_HUE); } double scale2 = (double) width * height / (fileMbr.getWidth() * fileMbr.getHeight()); double scale = Math.sqrt(scale2); // Create an image BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); Color bg_color = params.getColor("bgcolor", new Color(0, 0, 0, 0)); graphics.setBackground(bg_color); graphics.clearRect(0, 0, width, height); graphics.setColor(strokeColor); for (InputSplit split : splits) { if (hdfDataset != null) { // Read points from the HDF file RecordReader<NASADataset, NASAShape> reader = new HDFRecordReader(params, (FileSplit) split, hdfDataset, true); NASADataset dataset = reader.createKey(); while (reader.next(dataset, (NASAShape) shape)) { // Skip with a fixed ratio if adaptive sample is set if (adaptiveSample && Math.random() > adaptiveSampleRatio) continue; if (plotRange == null || shape.isIntersected(shape)) { shape.draw(graphics, fileMbr, width, height, 0.0); } } reader.close(); } else { RecordReader<Rectangle, Shape> reader = new ShapeRecordReader<Shape>(params, (FileSplit) split); Rectangle cell = reader.createKey(); while (reader.next(cell, shape)) { // Skip with a fixed ratio if adaptive sample is set if (adaptiveSample && Math.random() > adaptiveSampleRatio) continue; Rectangle shapeMBR = shape.getMBR(); if (shapeMBR != null) { if (plotRange == null || shapeMBR.isIntersected(plotRange)) { if (gradualFade) { double sizeInPixels = (shapeMBR.getWidth() + shapeMBR.getHeight()) * scale; if (sizeInPixels < 1.0 && Math.round(sizeInPixels * 255) < 1.0) { // This shape can be safely skipped as it is too small to be plotted continue; } else { int alpha = (int) Math.round(sizeInPixels * 255); graphics.setColor(new Color((alpha << 24) | color, true)); } } shape.draw(graphics, fileMbr, width, height, scale2); } } } reader.close(); } } // Write image to output graphics.dispose(); if (vflip) { AffineTransform tx = AffineTransform.getScaleInstance(1, -1); tx.translate(0, -image.getHeight()); AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); image = op.filter(image, null); } FileSystem outFs = outFile.getFileSystem(params); OutputStream out = outFs.create(outFile, true); ImageIO.write(image, "png", out); out.close(); }
From source file:com.xuggle.xuggler.UtilsTest.java
@SuppressWarnings("deprecation") @Test//from w ww .j ava2 s.co m public void testPictureToPictureWithRotate() { // note that the image is square in this test to make rotation // easier to handle int size = 50; int black = Color.BLACK.getRGB(); int white = Color.WHITE.getRGB(); // construct an image with black and white stripped columns BufferedImage image1 = new BufferedImage(size, size, BufferedImage.TYPE_3BYTE_BGR); for (int x = 0; x < size; ++x) for (int y = 0; y < size; ++y) { int color = x % 2 == 0 ? black : white; image1.setRGB(x, y, color); } // convert image1 to a picture and then back to image2 BufferedImage image2 = Utils.videoPictureToImage(Utils.imageToVideoPicture(image1, 0)); // rotae image2 AffineTransform t = AffineTransform.getRotateInstance(Math.PI / 2, image2.getWidth() / 2, image2.getHeight() / 2); AffineTransformOp ato = new AffineTransformOp(t, AffineTransformOp.TYPE_BICUBIC); BufferedImage image3 = new BufferedImage(size, size, BufferedImage.TYPE_3BYTE_BGR); ato.filter(image2, image3); // convert image2 to a picture and then back to image3 BufferedImage image4 = Utils.videoPictureToImage(Utils.imageToVideoPicture(image3, 0)); // test that image4 now contains stripped rows (not columns) for (int x = 0; x < size; ++x) for (int y = 0; y < size; ++y) { int pixel = image4.getRGB(x, y); int color = y % 2 == 0 ? black : white; assertTrue("color value missmatch", pixel == color); } }
From source file:org.apache.cocoon.reading.ImageReader.java
protected void processStream(InputStream inputStream) throws IOException, ProcessingException { if (hasTransform()) { if (getLogger().isDebugEnabled()) { getLogger().debug("image " + ((width == 0) ? "?" : Integer.toString(width)) + "x" + ((height == 0) ? "?" : Integer.toString(height)) + " expires: " + expires); }//from www . j ava 2 s.c om /* * NOTE (SM): * Due to Bug Id 4502892 (which is found in *all* JVM implementations from * 1.2.x and 1.3.x on all OS!), we must buffer the JPEG generation to avoid * that connection resetting by the peer (user pressing the stop button, * for example) crashes the entire JVM (yes, dude, the bug is *that* nasty * since it happens in JPEG routines which are native!) * I'm perfectly aware of the huge memory problems that this causes (almost * doubling memory consuption for each image and making the GC work twice * as hard) but it's *far* better than restarting the JVM every 2 minutes * (since this is the average experience for image-intensive web application * such as an image gallery). * Please, go to the <a href="http://developer.java.sun.com/developer/bugParade/bugs/4502892.html">Sun Developers Connection</a> * and vote this BUG as the one you would like fixed sooner rather than * later and all this hack will automagically go away. * Many deep thanks to Michael Hartle <mhartle@hartle-klug.com> for tracking * this down and suggesting the workaround. * * UPDATE (SM): * This appears to be fixed on JDK 1.4 */ try { byte content[] = readFully(inputStream); ImageIcon icon = new ImageIcon(content); BufferedImage original = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB); BufferedImage currentImage = original; currentImage.getGraphics().drawImage(icon.getImage(), 0, 0, null); if (width > 0 || height > 0) { double ow = icon.getImage().getWidth(null); double oh = icon.getImage().getHeight(null); if (usePercent) { if (width > 0) { width = Math.round((int) (ow * width) / 100); } if (height > 0) { height = Math.round((int) (oh * height) / 100); } } AffineTransformOp filter = new AffineTransformOp(getTransform(ow, oh, width, height), AffineTransformOp.TYPE_BILINEAR); WritableRaster scaledRaster = filter.createCompatibleDestRaster(currentImage.getRaster()); filter.filter(currentImage.getRaster(), scaledRaster); currentImage = new BufferedImage(original.getColorModel(), scaledRaster, true, null); } if (null != grayscaleFilter) { grayscaleFilter.filter(currentImage, currentImage); } if (null != colorFilter) { colorFilter.filter(currentImage, currentImage); } // JVM Bug handling if (JVMBugFixed) { JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage); p.setQuality(this.quality[0], true); encoder.setJPEGEncodeParam(p); encoder.encode(currentImage); } else { ByteArrayOutputStream bstream = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bstream); JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage); p.setQuality(this.quality[0], true); encoder.setJPEGEncodeParam(p); encoder.encode(currentImage); out.write(bstream.toByteArray()); } out.flush(); } catch (ImageFormatException e) { throw new ProcessingException( "Error reading the image. " + "Note that only JPEG images are currently supported."); } finally { // Bugzilla Bug 25069, close inputStream in finally block // this will close inputStream even if processStream throws // an exception inputStream.close(); } } else { // only read the resource - no modifications requested if (getLogger().isDebugEnabled()) { getLogger().debug("passing original resource"); } super.processStream(inputStream); } }
From source file:com.mucommander.ui.viewer.image.ImageViewer.java
private synchronized void zoom(double factor) { setFrameCursor(CURSOR_WAIT);//from w w w .j a v a 2 s . c o m final int srcWidth = image.getWidth(null); final int srcHeight = image.getHeight(null); final int scaledWidth = (int) (srcWidth * factor); final int scaledHeight = (int) (srcHeight * factor); if (factor != 1.0) { AbstractFile file = filesInDirectory.get(indexInDirectory); if ("svg".equalsIgnoreCase(file.getExtension())) { try { this.scaledImage = transcodeSVGDocument(file, scaledWidth, scaledHeight); } catch (IOException e) { e.printStackTrace(); } } else { this.scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB); AffineTransform at = new AffineTransform(); at.scale(factor, factor); AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); this.scaledImage = scaleOp.filter(this.image, this.scaledImage); } } else { this.scaledImage = image; } statusBar.setZoom(factor); checkZoom(); setFrameCursor(CURSOR_DEFAULT); }