Java Code Examples for java.awt.Image#getScaledInstance()

The following examples show how to use java.awt.Image#getScaledInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageUtils.java    From GpsPrune with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a scaled and smoothed image according to the specified size
 * @param inImage image to scale
 * @param inWidth width to scale to
 * @param inHeight height to scale to
 * @return BufferedImage containing scaled result
 */
public static BufferedImage createScaledImage(Image inImage, int inWidth, int inHeight)
{
	if (inWidth <= 0 || inHeight <= 0) {
		return null;
	}
	// create smaller image and force its loading
	Image smallerImage = inImage.getScaledInstance(inWidth, inHeight, Image.SCALE_SMOOTH);
	Image tempImage = new ImageIcon(smallerImage).getImage();
	tempImage.getWidth(null);

	// create buffered image to do transform
	BufferedImage buffer = new BufferedImage(inWidth, inHeight, BufferedImage.TYPE_INT_RGB);
	// copy scaled picture into buffer
	Graphics buffG = buffer.getGraphics();
	buffG.drawImage(smallerImage, 0, 0, inWidth, inHeight, null);
	buffG.dispose();

	// clear variables
	smallerImage = null; tempImage = null;
	// smooth scaled image using a normalized 3x3 matrix - taking next neighbour
	buffer = CONVOLVER.filter(buffer, null);

	return buffer;
}
 
Example 2
Source File: FileServiceApp.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private void previewData(byte[] data, String fileName, String type) {
	try {
		int w1 = this.centerPane.getWidth();
		int h1 = this.centerPane.getHeight();
		Image image = ImageIO.read(new ByteArrayInputStream(data));
		if (image == null) {
			JOptionPane.showMessageDialog(this, "The selected file cannot be previewed");
			return;
		}
		int w2 = image.getWidth(null);
		int h2 = image.getHeight(null);
		double[] dims = this.getScaledSize(w1, h1, w2, h2);
		JLabel label = new JLabel(new ImageIcon(image.getScaledInstance((int) dims[0], (int) dims[1], Image.SCALE_DEFAULT)));
		this.centerPane.removeAll();
		this.centerPane.add(label, BorderLayout.CENTER);
		this.centerPane.setBorder(BorderFactory.createTitledBorder("Preview - " + fileName));
		this.centerPane.validate();
	} catch (Exception e) {
		this.showError(e.getMessage());
	}
}
 
Example 3
Source File: DownApplication.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
private void initTray() throws AWTException {
  if (SystemTray.isSupported()) {
    // 获得系统托盘对象
    SystemTray systemTray = SystemTray.getSystemTray();
    // 获取图片所在的URL
    URL url = Thread.currentThread().getContextClassLoader().getResource(ICON_PATH);
    // 为系统托盘加托盘图标
    Image trayImage = Toolkit.getDefaultToolkit().getImage(url);
    Dimension trayIconSize = systemTray.getTrayIconSize();
    trayImage = trayImage.getScaledInstance(trayIconSize.width, trayIconSize.height, Image.SCALE_SMOOTH);
    trayIcon = new TrayIcon(trayImage, "Proxyee Down");
    systemTray.add(trayIcon);
    loadPopupMenu();
    //双击事件监听
    trayIcon.addActionListener(event -> Platform.runLater(() -> loadUri(null, true)));
  }
}
 
Example 4
Source File: GraphicUtils.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
    * Returns a scaled down image if the height or width is smaller than the
    * image size.
    * 
    * @param icon
    *            the image icon.
    * @param newHeight
    *            the preferred height.
    * @param newWidth
    *            the preferred width.
    * @return the icon.
    */
   public static ImageIcon scaleImageIcon(ImageIcon icon, int newHeight,
    int newWidth) {
Image img = icon.getImage();
int height = icon.getIconHeight();
int width = icon.getIconWidth();

if (height > newHeight) {
    height = newHeight;
}

if (width > newWidth) {
    width = newWidth;
}
img = img.getScaledInstance(width, height, Image.SCALE_DEFAULT);
return new ImageIcon(img);
   }
 
Example 5
Source File: GraphicUtils.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
    * Returns a scaled down image if the height or width is smaller than the
    * image size.
    * 
    * @param icon
    *            the image icon.
    * @param newHeight
    *            the preferred height.
    * @param newWidth
    *            the preferred width.
    * @return the icon.
    */
   public static ImageIcon scaleImageIcon(ImageIcon icon, int newHeight,
    int newWidth) {
Image img = icon.getImage();
int height = icon.getIconHeight();
int width = icon.getIconWidth();

if (height > newHeight) {
    height = newHeight;
}

if (width > newWidth) {
    width = newWidth;
}
img = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
return new ImageIcon(img);
   }
 
Example 6
Source File: TestJTextPaneHTMLRendering.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void createTestUI(JPanel panel) {
    textPane = new JTextPane();
    panel.add(textPane, BorderLayout.CENTER);

    final EditorKit l_kit = textPane.getEditorKitForContentType("text/html");
    textPane.setEditable(false);
    textPane.setEditorKit(l_kit);
    cache = (Dictionary<URL, Image>)textPane.getDocument().getProperty("imageCache");
    if (cache==null) {
        cache=new Hashtable<URL, Image>();
        textPane.getDocument().putProperty("imageCache",cache);
    }

    URL arrowLocationUrl = TestJTextPaneHTMLRendering.class.getResource("arrow.png");
    ImageIcon imageIcon = new ImageIcon(arrowLocationUrl);
    Image image = imageIcon.getImage();
    Image scaledImage = image.getScaledInstance(24, 24, java.awt.Image.SCALE_SMOOTH);
    cache.put(urlArrow, scaledImage);
    new Thread(TestJTextPaneHTMLRendering::runTest).start();
}
 
Example 7
Source File: GenericTableModel.java    From armitage with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Object getImageAt(JTable t, int row, String column, float zoomnow) {
	Image i = (Image)getValueAt(t, row, column);

	/* clear old whateverz */
	if (zoom != zoomnow) {
		zoom = zoomnow;
		imageCache = new HashMap();
	}

	/* check our cache */
	synchronized (this) {
		if (imageCache.containsKey(i)) {
			return (Image)imageCache.get(i);
		}
	}

	Image rs = i.getScaledInstance((int)Math.floor((i.getWidth(null) / 11.0) * zoom), (int)Math.floor((i.getHeight(null) / 11.0) * zoom),  java.awt.Image.SCALE_SMOOTH);

	synchronized (this) {
		imageCache.put(i, rs);
	}
	return rs;
}
 
Example 8
Source File: MultiResolutionCachedImageTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {

        Image image = new TestMultiResolutionCachedImage(100);

        image.getWidth(null);
        image.getHeight(null);
        image.getProperty("comment", null);

        int scaledSize = 50;
        Image scaledImage = image.getScaledInstance(scaledSize, scaledSize,
                Image.SCALE_SMOOTH);

        if (!(scaledImage instanceof BufferedImage)) {
            throw new RuntimeException("Wrong scaled image!");
        }

        BufferedImage buffScaledImage = (BufferedImage) scaledImage;

        if (buffScaledImage.getWidth() != scaledSize
                || buffScaledImage.getHeight() != scaledSize) {
            throw new RuntimeException("Wrong scaled image!");
        }

        if (buffScaledImage.getRGB(scaledSize / 2, scaledSize / 2) != TEST_COLOR.getRGB()) {
            throw new RuntimeException("Wrong scaled image!");
        }
    }
 
Example 9
Source File: ZxingHelper.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
/**
 * 插入LOGO
 * 
 * @param source
 *            二维码图片
 * @param imgPath
 *            LOGO图片地址
 * @param needCompress
 *            是否压缩
 * @throws Exception
 */
private void insertLogo(BufferedImage source, InputStream logo, boolean needCompress) throws Exception {
	Image src = ImageIO.read(logo);
	int width = src.getWidth(null);
	int height = src.getHeight(null);
	if (needCompress) { // 压缩LOGO
		if (width > logoSize) {
			width = logoSize;
		}
		if (height > logoSize) {
			height = logoSize;
		}
		Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
		BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = tag.getGraphics();
		g.drawImage(image, 0, 0, null); // 绘制缩小后的图
		g.dispose();
		src = image;
	}
	// 插入LOGO
	Graphics2D graph = source.createGraphics();
	int x = (imageSize - width) / 2;
	int y = (imageSize - height) / 2;
	graph.drawImage(src, x, y, width, height, null);
	Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
	graph.setStroke(new BasicStroke(3f));
	graph.draw(shape);
	graph.dispose();
}
 
Example 10
Source File: GraphicUtils.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
    * Returns a scaled down image if the height or width is smaller than the
    * image size.
    * 
    * @param icon
    *            the image icon.
    * @param newHeight
    *            the preferred height.
    * @param newWidth
    *            the preferred width.
    * @return the icon.
    */
   public static ImageIcon scale(ImageIcon icon, int newHeight, int newWidth) {
Image img = icon.getImage();
int height = icon.getIconHeight();
int width = icon.getIconWidth();
boolean scaleHeight = height * newWidth > width * newHeight;
if (height > newHeight) {
    // Too tall
    if (width <= newWidth || scaleHeight) {
	// Width is okay or height is limiting factor due to aspect
	// ratio
	height = newHeight;
	width = -1;
    } else {
	// Width is limiting factor due to aspect ratio
	height = -1;
	width = newWidth;
    }
} else if (width > newWidth) {
    // Too wide and height is okay
    height = -1;
    width = newWidth;
} else if (scaleHeight) {
    // Height is limiting factor due to aspect ratio
    height = newHeight;
    width = -1;
} else {
    // Width is limiting factor due to aspect ratio
    height = -1;
    width = newWidth;
}
img = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
return new ImageIcon(img);
   }
 
Example 11
Source File: ButtonOverlayControl.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private ButtonDef(Action action, Dimension buttonDimension, int numCols, String toolTipText) {
    this.action = action;
    this.numCols = numCols;
    this.toolTipText = toolTipText;
    Image rawImage = iconToImage((Icon) this.action.getValue(Action.LARGE_ICON_KEY));
    image = rawImage.getScaledInstance(buttonDimension.width,
                                       buttonDimension.height,
                                       Image.SCALE_SMOOTH);
    shape = new RoundRectangle2D.Double();
    shape.arcwidth = 4;
    shape.archeight = 4;
    shape.setFrame(new Point(), buttonDimension);
}
 
Example 12
Source File: MetaDataPanel.java    From mvisc with GNU General Public License v3.0 5 votes vote down vote up
public void maximizeImage(boolean b)
	{
		if (b)
		{
			Image resizedImage = null;
			Image img = null;
			try
			{
				//TODO
				if (currentData==null)
					img = ImageIO.read(new File(Settings.imgPath + "/bt/2014/BauchbilderBa_BIL1/05_BauchbilderBa_16_05_2014_BIL/14Ba_0021.JPG"));
				else
					img = ImageIO.read(new File(currentData.getFileName()));
				
				resizedImage = img.getScaledInstance(GUISettings.defaultImageCompareWidth, dph, Image.SCALE_SMOOTH);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			icon.setImage(resizedImage);
			
			imgLabel.setPreferredSize(new Dimension(GUISettings.defaultImageCompareWidth, dph));
			imgHoverEnabled = false;
			this.dataPanel.setVisible(false);
			
		}
		else
		{
			imgHoverEnabled = true;
			imgLabel.setPreferredSize(new Dimension(iw, 268));
			this.dataPanel.setVisible(false);
		}
		this.revalidate();
		this.repaint();
//		this.zooPanel.setMinimumSize(new Dimension(dpw, dph));
//		this.zooPanel.setPreferredSize(new Dimension(dpw, dph));
	}
 
Example 13
Source File: QRCodeUtil.java    From JavaWeb with Apache License 2.0 5 votes vote down vote up
private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
    File file = new File(imgPath);
    if (!file.exists()) {
        System.err.println(""+imgPath+"   该文件不存在!");
        return;
    }
    Image src = ImageIO.read(new File(imgPath));
    int width = src.getWidth(null);
    int height = src.getHeight(null);
    if (needCompress) { //压缩LOGO
        if (width > WIDTH) {
            width = WIDTH;
        }
        if (height > HEIGHT) {
            height = HEIGHT;
        }
        Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, null); // 绘制缩小后的图
        g.dispose();
        src = image;
    }
    //插入LOGO
    Graphics2D graph = source.createGraphics();
    int x = (QRCODE_SIZE - width) / 2;
    int y = (QRCODE_SIZE - height) / 2;
    graph.drawImage(src, x, y, width, height, null);
    Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
    graph.setStroke(new BasicStroke(3f));
    graph.draw(shape);
    graph.dispose();
}
 
Example 14
Source File: ImageUtils.java    From ocular with GNU General Public License v3.0 5 votes vote down vote up
private static void refreshViewer(Image img, AtomicInteger zoomX, AtomicInteger zoomY, ImageIcon icon, Frame frame) {
	//System.err.println(zoomX);
	//System.err.println(zoomY);
	Image newImage;
	if (zoomX.get() == 1 && zoomY.get() == 1) {
		newImage = img;
	} else {
		newImage = img.getScaledInstance((int)(img.getWidth(frame) * Math.pow(2, zoomX.get())),
				(int)(img.getHeight(frame) * Math.pow(2, zoomY.get())),
				Image.SCALE_SMOOTH);
	}
	icon.setImage(newImage);
	frame.repaint();
}
 
Example 15
Source File: WindowGui.java    From winthing with Apache License 2.0 5 votes vote down vote up
public void setIcon(boolean color) {
    SystemTray tray = SystemTray.getSystemTray();
    TrayIcon[] icons = tray.getTrayIcons();
    if (icons.length > 0) {
        String name = color ? "favicon-green.png" : "favicon-red.png";

        URL url = getClass().getClassLoader().getResource(name);
        Image image = Toolkit.getDefaultToolkit().getImage(url);

        int trayWidth = tray.getTrayIconSize().width;
        int trayHeight = tray.getTrayIconSize().height;
        Image scaled = image.getScaledInstance(trayWidth, trayHeight, Image.SCALE_SMOOTH);
        icons[0].setImage(scaled);
    }
}
 
Example 16
Source File: Images.java    From hermes with Apache License 2.0 4 votes vote down vote up
/**
 * Crop an image
 * 
 * @param originalImage
 *            The image file
 * @param to
 *            The destination file
 * @param x1
 *            The new x origin
 * @param y1
 *            The new y origin
 * @param width
 *            The new width
 * @param height
 *            The new height
 * @param imgWidth
 *            The widht of img
 * @param imgHeight
 *            The height of img
 */
public static Map<String, String> crop(MultipartFile originalImage, int x1, int y1, int width, int height, int imgWidth, int imgHeight) {
	try {
		ByteArrayInputStream bais = new ByteArrayInputStream(originalImage.getBytes());
		MemoryCacheImageInputStream mciis = new MemoryCacheImageInputStream(bais);
		BufferedImage source = ImageIO.read(mciis);
		int owidth = source.getWidth();// 图片原始宽度
		int oheight = source.getHeight();// 图片原始长度
		double ratioW = (double) width / imgWidth; // 原始图片与前台图片显示宽度的比例
		double ratioH = (double) height / imgHeight;

		int cutW = (int) (owidth * ratioW);// 裁剪图片的真实宽度
		int cutH = (int) (oheight * ratioH);

		double ratioX = (double) x1 / imgWidth; // x坐标所在位置的比例
		double ratioY = (double) y1 / imgHeight;

		int xo = (int) (owidth * ratioX);// 图片裁剪开始的真实X坐标
		int yo = (int) (oheight * ratioY);
		// crop 图片
		BufferedImage dest = new BufferedImage(cutW, cutH, BufferedImage.TYPE_INT_RGB);
		Image croppedImage = source.getSubimage(xo, yo, cutW, cutH);
		Graphics graphics = dest.getGraphics();
		graphics.setColor(Color.WHITE);
		graphics.fillRect(0, 0, cutW, cutH);
		graphics.drawImage(croppedImage, 0, 0, null);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(dest, Files.getExt(originalImage.getOriginalFilename()), baos);
		byte[] bytes = baos.toByteArray();
		String avatar_lg = String.format(BASE64, Files.getMimeType(originalImage.getOriginalFilename()), new String(Base64.encodeBase64(bytes)));

		// resize图片
		BufferedImage destResize = new BufferedImage(46, 46, BufferedImage.TYPE_INT_RGB);
		Image resizeImage = croppedImage.getScaledInstance(46, 46, Image.SCALE_SMOOTH);
		Graphics graphicsResize = destResize.getGraphics();
		graphicsResize.setColor(Color.WHITE);
		graphicsResize.fillRect(0, 0, 46, 46);
		graphicsResize.drawImage(resizeImage, 0, 0, null);
		ByteArrayOutputStream baosResize = new ByteArrayOutputStream();
		ImageIO.write(destResize, Files.getExt(originalImage.getOriginalFilename()), baosResize);
		byte[] bytesResize = baosResize.toByteArray();
		String avatar = String.format(BASE64, Files.getMimeType(originalImage.getOriginalFilename()), new String(Base64.encodeBase64(bytesResize)));

		Map<String, String> map = new HashMap<String, String>();
		map.put("avatar_lg", avatar_lg);
		map.put("avatar", avatar);
		return map;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}

}
 
Example 17
Source File: MediaUtils.java    From desktopclient-java with GNU General Public License v3.0 4 votes vote down vote up
private static Image scaleImage(Image image, int width, int height) {
    return image.getScaledInstance(width, height, Image.SCALE_FAST);
}
 
Example 18
Source File: ImageUtil.java    From oim-fx with MIT License 4 votes vote down vote up
public static ImageIcon getImageIcon(Image image, int w, int h) {
    image = image.getScaledInstance(w, h, Image.SCALE_SMOOTH);
    return new ImageIcon(image);
}
 
Example 19
Source File: ImageUtil.java    From oim-fx with MIT License 4 votes vote down vote up
public static Icon getIcon(Image image, int w, int h) {
    image = image.getScaledInstance(w, h, Image.SCALE_SMOOTH);
    return new ImageIcon(image);
}
 
Example 20
Source File: Acao.java    From brModelo with GNU General Public License v3.0 4 votes vote down vote up
private ImageIcon reescale(Image img) {
    Image newimg = img.getScaledInstance(16, 16, java.awt.Image.SCALE_SMOOTH);
    return new ImageIcon(newimg);
}