/** * 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); }
/** Get the outline of a character given the glyph id */ protected synchronized GeneralPath getOutline(int glyphId, float width) { // find the glyph itself GlyfTable glyf = (GlyfTable) this.font.getTable("glyf"); Glyf g = glyf.getGlyph(glyphId); GeneralPath gp = null; if (g instanceof GlyfSimple) { gp = renderSimpleGlyph((GlyfSimple) g); } else if (g instanceof GlyfCompound) { gp = renderCompoundGlyph(glyf, (GlyfCompound) g); } else { gp = new GeneralPath(); } // calculate the advance HmtxTable hmtx = (HmtxTable) this.font.getTable("hmtx"); float advance = hmtx.getAdvance(glyphId) / this.unitsPerEm; // scale the glyph to match the desired advance float widthfactor = width / advance; // the base transform scales the glyph to 1x1 AffineTransform at = AffineTransform.getScaleInstance(1 / this.unitsPerEm, 1 / this.unitsPerEm); at.concatenate(AffineTransform.getScaleInstance(widthfactor, 1)); gp.transform(at); return gp; }
@Override public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; Dimension d = this.getSize(); int width = (int) d.getWidth(); int height = (int) d.getHeight(); g2.clearRect(0, 0, width, height); AffineTransform at = null; if (cachedImage == null) { renderOffscreen(); } if (getOrientation() == SwingConstants.VERTICAL) { at = AffineTransform.getScaleInstance((double) width / 10f, (double) height / DEFAULT_HEIGHT); } if (getOrientation() == SwingConstants.HORIZONTAL) { at = AffineTransform.getScaleInstance( (double) width / DEFAULT_WIDTH, (double) height / (double) 10); } drawBackground(g2); g2.drawRenderedImage(cachedImage, at); }
/** @throws RuntimeException */ private void calculateAffineTransform() { if (extent == null) { return; } else if (image == null || getWidth() == 0 || getHeight() == 0) { return; } if (adjustExtent) { double escalaX = getWidth() / extent.getWidth(); double escalaY = getHeight() / extent.getHeight(); double xCenter = extent.getMinX() + extent.getWidth() / 2.0; double yCenter = extent.getMinY() + extent.getHeight() / 2.0; adjustedExtent = new Envelope(); double scale; if (escalaX < escalaY) { scale = escalaX; double newHeight = getHeight() / scale; double newX = xCenter - (extent.getWidth() / 2.0); double newY = yCenter - (newHeight / 2.0); adjustedExtent = new Envelope(newX, newX + extent.getWidth(), newY, newY + newHeight); } else { scale = escalaY; double newWidth = getWidth() / scale; double newX = xCenter - (newWidth / 2.0); double newY = yCenter - (extent.getHeight() / 2.0); adjustedExtent = new Envelope(newX, newX + newWidth, newY, newY + extent.getHeight()); } trans.setToIdentity(); trans.concatenate(AffineTransform.getScaleInstance(scale, -scale)); trans.concatenate( AffineTransform.getTranslateInstance( -adjustedExtent.getMinX(), -adjustedExtent.getMinY() - adjustedExtent.getHeight())); } else { adjustedExtent = new Envelope(extent); trans.setToIdentity(); double scaleX = getWidth() / extent.getWidth(); double scaleY = getHeight() / extent.getHeight(); /** Map Y axis grows downward but CRS grows upward => -1 */ trans.concatenate(AffineTransform.getScaleInstance(scaleX, -scaleY)); trans.concatenate( AffineTransform.getTranslateInstance( -extent.getMinX(), -extent.getMinY() - extent.getHeight())); } try { transInv = trans.createInverse(); } catch (NoninvertibleTransformException ex) { transInv = null; throw new RuntimeException(ex); } }
/** @author JG uniCenta */ public class BasicTicketForScreen extends BasicTicket { private static Font BASEFONT = new Font("Monospaced", Font.PLAIN, 12) .deriveFont(AffineTransform.getScaleInstance(1.0, 1.40)); private static int FONTHEIGHT = 20; private static double IMAGE_SCALE = 1.0; /** @return */ @Override protected Font getBaseFont() { return BASEFONT; } /** @return */ @Override protected int getFontHeight() { return FONTHEIGHT; } /** @return */ @Override protected double getImageScale() { return IMAGE_SCALE; } }
private synchronized void initBars() { if (bars != null) { return; } bars = new Area[BAR_COUNT]; final double fixedAngle = 2.0 * Math.PI / (double) bars.length; for (int i = 0; i < bars.length; ++i) { Area primitive = makeBar(); Point2D.Double center = new Point2D.Double((double) DIAMETER / 2, (double) DIAMETER / 2); AffineTransform toCircle = AffineTransform.getRotateInstance( ((double) -i) * fixedAngle, center.getX(), center.getY()); AffineTransform toBorder = AffineTransform.getTranslateInstance(45.0, -6.0); AffineTransform toScale = AffineTransform.getScaleInstance(0.1, 0.1); primitive.transform(toBorder); primitive.transform(toCircle); primitive.transform(toScale); bars[i] = primitive; } }
/** * Get a glyph outline by character code * * <p>Note this method must always return an outline * * @param src the character code of the desired glyph * @return the glyph outline */ @Override protected GeneralPath getOutline(char src, float width) { // some true type fonts put characters in the undefined // region of Unicode instead of as normal characters. if (!this.f.canDisplay(src) && this.f.canDisplay((char) (src + 0xf000))) { src += 0xf000; } // filter out control characters for (int i = 0; i < controlChars.length; i++) { if (controlChars[i] == src) { src = (char) (0xf000 | src); break; } } char[] glyph = new char[1]; glyph[0] = src; GlyphVector gv = this.f.createGlyphVector(this.basecontext, glyph); GeneralPath gp = new GeneralPath(gv.getGlyphOutline(0)); // this should be gv.getGlyphMetrics(0).getAdvance(), but that is // broken on the Mac, so we need to read the advance from the // hmtx table in the font CMap map = this.cmapTable.getCMap(mapIDs[0], mapIDs[1]); int glyphID = map.map(src); float advance = (float) this.hmtxTable.getAdvance(glyphID) / (float) this.unitsPerEm; float widthfactor = width / advance; gp.transform(AffineTransform.getScaleInstance(widthfactor, -1)); return gp; }
@Override public AffineTransform getTransform(Component componentArgument) { AffineTransform transform = AffineTransform.getScaleInstance(1.0, -1.0); transform.translate(0, -(componentArgument.getHeight() * 2)); return transform; }
/** * Perform a zooming operation centered on the given point (dx, dy) and using the given scale * factor. The given AffineTransform instance is preconcatenated. * * @param dx center x * @param dy center y * @param scale zoom rate * @param af original affinetransform */ public void centerZoom(double dx, double dy, double scale, AffineTransform af) { af.preConcatenate(AffineTransform.getTranslateInstance(-dx, -dy)); af.preConcatenate(AffineTransform.getScaleInstance(scale, scale)); af.preConcatenate(AffineTransform.getTranslateInstance(dx, dy)); transform = af; syncScrollBars(); }
private void drawArrow(Graphics2D g2d, double sx, double sy, double px, double py, int pass) { if (pass == 0) { g2d.setStroke(new BasicStroke(4.0f)); g2d.setPaint(preSynapticSiteColor.brighter()); g2d.draw(new Line2D.Double(sx, sy, px, py)); return; } double dx = px - sx; double dy = py - sy; Polygon tip = new Polygon(); tip.addPoint(0, 0); tip.addPoint(-10, -20); tip.addPoint(10, -20); AffineTransform transform = new AffineTransform(); transform.concatenate(AffineTransform.getTranslateInstance(px, py)); transform.concatenate(AffineTransform.getScaleInstance(0.5, 0.5)); transform.concatenate(AffineTransform.getRotateInstance(Math.atan2(dy, dx) - Math.PI * 0.5)); Shape shape = new GeneralPath(tip).createTransformedShape(transform); g2d.setPaint(preSynapticSiteColor.darker().darker()); g2d.draw(shape); g2d.setPaint(preSynapticSiteColor.brighter().brighter()); g2d.fill(shape); }
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; }
/** * Apply the current scaling transformation to the figure. * * @param figure The figure the transformation is to be applied to. * @exception IllegalActionException If the getToken() method throws such an exception. */ protected void _applyTransform(Figure figure) throws IllegalActionException { double scaleFactorXValue = 1.0; double scaleFactorYValue = 1.0; boolean needsTransform = false; if ((scaleFactorX.isOutsideConnected()) && scaleFactorX.hasToken(0)) { scaleFactorXValue = ((DoubleToken) scaleFactorX.get(0)).doubleValue(); needsTransform = true; } if ((scaleFactorY.isOutsideConnected()) && scaleFactorY.hasToken(0)) { scaleFactorYValue = ((DoubleToken) scaleFactorY.get(0)).doubleValue(); needsTransform = true; } if (needsTransform) { if (_isAccumulating()) { scaleFactorXValue *= _oldScaleFactorX; scaleFactorYValue *= _oldScaleFactorY; } _oldScaleFactorX = scaleFactorXValue; _oldScaleFactorY = scaleFactorYValue; AffineTransform inputTransform = AffineTransform.getScaleInstance(scaleFactorXValue, scaleFactorYValue); figure.transform(inputTransform); } }
public AffineTransform getAffineTransform( int scaleFrom, Position pos, Rotation rotation, double ratio) { AffineTransform t = getAffineTransform(pos, rotation); AffineTransform scale = AffineTransform.getScaleInstance(ratio, ratio); t.concatenate(scale); return t; }
public GraphicSet importSetFromFile(File inputFile, List<String> warnings) throws ImportException { Writer out = null; try { // Get a DOMImplementation DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); // Create an instance of org.w3c.dom.Document Document document = domImpl.createDocument(null, "svg", null); // Create an instance of the SVG Generator final SVGGraphics2D svgGenerator = new SVGGraphics2D(document); svgGenerator.setTransform(new AffineTransform()); // Open input file PSInputFile in = new PSInputFile(inputFile.getAbsolutePath()); Rectangle2D bb = this.getBoundingBox(inputFile); svgGenerator.setTransform(AffineTransform.getTranslateInstance(-bb.getX(), -bb.getY())); Dimension d = new Dimension((int) bb.getWidth(), (int) bb.getHeight()); // Create processor and associate to input and output file Processor processor = new Processor(svgGenerator, d, false); processor.setData(in); // Process processor.process(); File tmp = File.createTempFile("temp", "svg"); tmp.deleteOnExit(); svgGenerator.stream(new FileWriter(tmp)); GraphicSet result = new SVGImporter().importSetFromFile(tmp, warnings); // Assume the EPS has been created with 72DPI (from Inkscape) double px2mm = Util.inch2mm(1d / 72d); result.setBasicTransform(AffineTransform.getScaleInstance(px2mm, px2mm)); return result; } catch (Exception ex) { Logger.getLogger(EPSImporter.class.getName()).log(Level.SEVERE, null, ex); throw new ImportException(ex); } }
/** * 画像のリサイズ * * @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; }
/** * Returns a default rendering of this <code>RenderableImage</code>. In all cases the area of * interest will equal the image bounds. Any hints set on the node via <code>setRenderingHints() * </code> will be used. * * <p>The dimensions of the created <code>RenderedImage</code> are determined in the following * order of precedence: * * <ol> * <li>If a <code>JAI.KEY_DEFAULT_RENDERING_SIZE</code> hint is set on the node it is used * unless both its dimensions are non-positive. * <li>The value returned by <code>JAI.getDefaultRenderingSize()</code> is used unless it is * <code>null</code>. * <li>An identity transform from renderable to rendered coordinates is applied. * </ol> * * Either dimension of the default rendering size set in the hints or on the default <code>JAI * </code> instance may be non-positive in which case the other dimension and the renderable * aspect ratio will be used to compute the rendered image size. * * <p>This method does not validate sources and parameters supplied in the <code>ParameterBlock * </code> supplied at construction against the specification of the operation this node * represents. It is the caller's responsibility to ensure that the data in the <code> * ParameterBlock</code> are suitable for this operation. Otherwise, some kind of exception or * error will occur. Invoking this method will cause any <code>DeferredData</code> parameters to * be evaluated. * * @return The default RenderedImage. */ public RenderedImage createDefaultRendering() { // Get the default dimensions. Dimension defaultDimension = null; RenderingHints hints = nodeSupport.getRenderingHints(); if (hints != null && hints.containsKey(JAI.KEY_DEFAULT_RENDERING_SIZE)) { defaultDimension = (Dimension) hints.get(JAI.KEY_DEFAULT_RENDERING_SIZE); } if (defaultDimension == null || (defaultDimension.width <= 0 && defaultDimension.height <= 0)) { defaultDimension = JAI.getDefaultRenderingSize(); } // Initialize scale factors to represent the identify transform. double sx = 1.0; double sy = 1.0; // Reset the scale factors if a default dimension is set. if (defaultDimension != null && (defaultDimension.width > 0 || defaultDimension.height > 0)) { if (defaultDimension.width > 0 && defaultDimension.height > 0) { sx = defaultDimension.width / getWidth(); sy = defaultDimension.height / getHeight(); } else if (defaultDimension.width > 0) { sx = sy = defaultDimension.width / getWidth(); } else { // defaultDimension.height > 0 sx = sy = defaultDimension.height / getHeight(); } } // Create the renderable-to-rendered scaling. AffineTransform transform = AffineTransform.getScaleInstance(sx, sy); // Return the rendering applying the computed transform. return createRendering(new RenderContext(transform)); }
public void paint(Graphics2D g) { Font origFont = g.getFont(); g.setRenderingHint( java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON); // 1) create scaled font Font font = origFont.deriveFont(AffineTransform.getScaleInstance(1.5, 3)); g.setFont(font); g.drawString("Scaled Font", 20, 40); // 2) create translated font font = origFont.deriveFont(AffineTransform.getTranslateInstance(50, 20)); g.setFont(font); g.drawString("Translated Font", 20, 80); g.drawLine(20, 80, 120, 80); // 3) create sheared font font = origFont.deriveFont(AffineTransform.getShearInstance(.5, .5)); g.setFont(font); g.drawString("Sheared Font", 20, 120); // 4) create rotated font font = origFont.deriveFont(AffineTransform.getRotateInstance(Math.PI / 4)); g.setFont(font); g.drawString("Rotated Font", 220, 120); }
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); }
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; }
private BufferedImage scale(BufferedImage image, int newWidth, int newHeight) { float width; float height; if (newWidth <= 0 || newHeight <= 0) { logger.warn("Invalid scale attempt aborted."); return null; } width = (float) newWidth / (float) image.getWidth(); height = (float) newHeight / (float) image.getHeight(); BufferedImage out = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = out.createGraphics(); RenderingHints qualityHints = new RenderingHints( RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ANTIALIAS_ON); qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2.setRenderingHints(qualityHints); AffineTransform at = AffineTransform.getScaleInstance(width, height); g2.drawImage(image, at, null); g2.dispose(); return out; }
public void render(Graphics2D g, Dimension d) { int n = this.problemScore.getAttempts(); n += this.problemScore.getPendings(); String text = "" + n; Color baseColor; if (this.problemScore.isSolved()) { baseColor = Color.GREEN; text += " / " + this.problemScore.getSolutionTime(); } else if (this.problemScore.isPending()) { baseColor = Color.BLUE.brighter(); } else if (this.problemScore.getAttempts() > 0) { baseColor = Color.RED; } else { baseColor = new Color(0, 0, 0, 0); } // g.fillRect(0, 0, d.width, d.height); ShadedRectangle.drawShadedRoundRect(g, baseColor, 0, 0, d.width, d.height, d.height / 3f); g.setColor(Color.BLACK); Font backup = g.getFont(); double magicScale = d.height / 20f; Font nfont = backup.deriveFont(AffineTransform.getScaleInstance(magicScale, magicScale)); Rectangle2D rect = new Rectangle2D.Float(0, 0, d.width, d.height); Utility.drawString3D(g, text, rect, nfont, Alignment.center); }
/** * This method used for transformation of the image. * * @param scale double * @param srcImg BufferedImage * @return BufferedImage */ private BufferedImage scale(double scale, BufferedImage srcImg) { if (scale == 1) { return srcImg; } AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(scale, scale), null); return op.filter(srcImg, null); }
private Image createImage(ImageProducer producer, int width, int height) { AffineTransform tx = AffineTransform.getScaleInstance(1.0, -1.0); tx.translate(0, -height); AffineTransformOp txop = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); FilteredImageSource src = new FilteredImageSource(producer, new BufferedImageFilter(txop)); return Toolkit.getDefaultToolkit().createImage(src); }
CustomGraphicLayer resizeCustomGraphicsLayer( CustomGraphicLayer cg, double widthScale, double heightScale) { removeCustomGraphic(cg); AffineTransform scale = AffineTransform.getScaleInstance(widthScale, heightScale); CustomGraphicLayer newCG = cg.transform(scale); addCustomGraphic(newCG); return newCG; }
private BufferedImage rotateImage180(BufferedImage image) { // Flip the image vertically and horizontally; equivalent to rotating the image 180 degrees AffineTransform tx = AffineTransform.getScaleInstance(-1, -1); tx.translate(-image.getWidth(null), -image.getHeight(null)); AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); image = op.filter(image, null); return image; }
private Rectangle getScaledRectangle(Rectangle rectangle) { final AffineTransform i2mTransform = ImageManager.getImageToModelTransform(product.getGeoCoding()); final double scaleX = i2mTransform.getScaleX(); final double scaleY = i2mTransform.getScaleY(); double scaleFactorY = Math.abs(scaleY / scaleX); final AffineTransform scaleTransform = AffineTransform.getScaleInstance(1.0, scaleFactorY); return scaleTransform.createTransformedShape(rectangle).getBounds(); }
/** * Scale the given BufferedImage to the given width and height. Return the new scaled * BufferedImage. */ public static BufferedImage scale(BufferedImage bsrc, int width, int height) { AffineTransform at = AffineTransform.getScaleInstance( (double) width / bsrc.getWidth(), (double) height / bsrc.getHeight()); BufferedImage bdest = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = bdest.createGraphics(); g.drawRenderedImage(bsrc, at); return bdest; }
/** * 缩放图像(按高度和宽度缩放) * * @param srcImageFile 源图像文件地址 * @param result 缩放后的图像地址 * @param height 缩放后的高度 * @param width 缩放后的宽度 * @param bb 比例不对时是否需要补白:true为补白; false为不补白; */ @SuppressWarnings("static-access") public static final void scale2( String srcImageFile, String result, int height, int width, boolean bb) { try { double ratio = 0.0; // 缩放比例 File f = new File(srcImageFile); BufferedImage bi = ImageIO.read(f); Image itemp = bi.getScaledInstance( width, height, bi.SCALE_SMOOTH); // bi.SCALE_SMOOTH 选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。 // 计算比例 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(); } AffineTransformOp op = new AffineTransformOp( AffineTransform // 仿射转换 .getScaleInstance(ratio, ratio), null); // 返回表示剪切变换的变换 itemp = op.filter(bi, null); // 转换源 BufferedImage 并将结果存储在目标 BufferedImage 中。 } if (bb) { // 补白 BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB); // 构造一个类型为预定义图像类型之一的 BufferedImage。 Graphics2D g = image.createGraphics(); // 创建一个 Graphics2D,可以将它绘制到此 BufferedImage 中。 g.setColor(Color.white); // 控制颜色 g.fillRect(0, 0, width, height); // 使用 Graphics2D 上下文的设置,填充 Shape 的内部区域。 if (width == itemp.getWidth(null)) g.drawImage( itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null); else g.drawImage( itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null); g.dispose(); itemp = image; } ImageIO.write((BufferedImage) itemp, "JPEG", new File(result)); } catch (IOException e) { e.printStackTrace(); } }
private CustomGraphicLayer syncSize( CyCustomGraphics<CustomGraphicLayer> graphics, final CustomGraphicLayer cg, double width, double height) { // final double nodeW = this.getWidth(); // final double nodeH = this.getHeight(); final Rectangle2D originalBounds = cg.getBounds2D(); // If this is just a paint, getBounds2D will return null and // we can use our own width and height if (originalBounds == null) return cg; if (width == 0.0 || height == 0.0) return cg; final double cgW = originalBounds.getWidth(); final double cgH = originalBounds.getHeight(); // In case size is same, return the original. if (width == cgW && height == cgH) return cg; final AffineTransform scale; final float fit = graphics.getFitRatio(); // Case 1: if custom graphic is a vector fit width and length if (cg instanceof PaintedShape || cg instanceof Cy2DGraphicLayer) { scale = AffineTransform.getScaleInstance(fit * width / cgW, fit * height / cgH); } else { double scaleW = width / cgW; double scaleH = height / cgH; // Case 2: node height value is larger than width if (scaleW >= scaleH) { scale = AffineTransform.getScaleInstance(fit * scaleH, fit * scaleH); // scale = AffineTransform.getScaleInstance(fit * (width / cgW) * (height / width), fit * // height / cgH); } else { scale = AffineTransform.getScaleInstance(fit * scaleW, fit * scaleW); // scale = AffineTransform.getScaleInstance(fit * (width / cgW) * (height / width), fit * // height / cgH); } } return cg.transform(scale); }
@Test public void testSetTransform() throws Exception { GeometryFactory factory = new GeometryFactory(); Polygon poly = createPolygon(factory, 10); EditBlackboard map = new EditBlackboard(SCREEN.x, SCREEN.y, transform, layerToWorld); Map<Geometry, EditGeom> mapping = map.setGeometries(poly, null); EventListener l = new EventListener(); map.getListeners().add(l); // test equal transform map.setToScreenTransform(new AffineTransform(transform)); assertTranslation(map, mapping.get(poly), 0, 0); assertNull(l.event); assertEquals(Point.valueOf(30, 25), map.toPoint(new Coordinate(20.5, 20.5))); assertEquals(new Coordinate(20.5, 20.5), map.toCoord(Point.valueOf(30, 25))); // test translated transform map.setToScreenTransform(AffineTransform.getTranslateInstance(0, 0)); assertTranslation(map, mapping.get(poly), -10, -5); EditBlackboardEvent event = findEvent(EventType.TRANFORMATION, l); assertNotNull(event); assertEquals(new AffineTransform(transform), event.getOldValue()); assertEquals(Point.valueOf(20, 20), map.toPoint(new Coordinate(20.5, 20.5))); assertEquals(new Coordinate(20.5, 20.5), map.toCoord(Point.valueOf(20, 20))); l.allEvents.clear(); map = new EditBlackboard( SCREEN.x, SCREEN.y, AffineTransform.getScaleInstance(.5, .5), layerToWorld); map.getListeners().add(l); mapping = map.setGeometries(poly, null); map.setCollapseVertices(false); map.setToScreenTransform(AffineTransform.getTranslateInstance(10, 5)); assertTranslation(map, mapping.get(poly), 0, 0); event = findEvent(EventType.TRANFORMATION, l); assertNotNull(event); assertEquals(AffineTransform.getScaleInstance(.5, .5), event.getOldValue()); assertEquals(Point.valueOf(30, 25), map.toPoint(new Coordinate(20.5, 20.5))); assertEquals(new Coordinate(20.5, 20.5), map.toCoord(Point.valueOf(30, 25))); }