Java Code Examples for java.awt.image.BufferedImage#getScaledInstance()

The following examples show how to use java.awt.image.BufferedImage#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: ImgUtils.java    From mvisc with GNU General Public License v3.0 6 votes vote down vote up
public static Image getThumbnailAsImage(String originalFileName, int width, int height) {
	
	String outputFileName = originalFileName.substring(0, originalFileName.length()-4) + ".tn.jpg";
	Image thumbnailImage = null;
	
	try{
		File thumbnailFile = new File(outputFileName);
		if (thumbnailFile.exists())
			thumbnailImage = ImageIO.read(thumbnailFile);
		else
		{
			BufferedImage img = ImageIO.read(new File(originalFileName));
			thumbnailImage = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
			ImageIO.write(ImgUtils.toBufferedImage(thumbnailImage), "jpg", thumbnailFile);
		}
		return thumbnailImage;
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
	return null;
}
 
Example 2
Source File: TemplateImage.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Override
public void doDraw(GraphicsContext graphic, ImageDefinedData data) {
	Image img = null;
	if(data.getWidth()!=null && data.getHeight()!=null){
		BufferedImage imgBuf = ImageUtils.readBufferedImage(graphic.getData());
		img = imgBuf.getScaledInstance(data.getWidth(), data.getHeight(), Image.SCALE_SMOOTH);
	}else{
		img = ImageUtils.createImageIcon(graphic.getData()).getImage();
	}
	int x = data.getX();
	int y = data.getY();
	if(data.getHorizontal()!=null){
		x = data.getHorizontal().getX(graphic, data.getWidth(graphic, img));
	}
	graphic.graphics.drawImage(img, x, y, null);
}
 
Example 3
Source File: baseDrawerItem.java    From brModelo with GNU General Public License v3.0 6 votes vote down vote up
public void DrawImagem(Graphics2D g) {
    BufferedImage img = getImagem();
    if (img == null) {
        return;
    }
    int[] pts = ArrayDePontos(getPosiImagem());
    if (pts.length != 4) {
        posiImagem = "L,T,200,200";
        imgres = null;
        pts = ArrayDePontos(getPosiImagem());
    }
    Rectangle rec = new Rectangle(pts[0], pts[1], pts[2], pts[3]);
    rec.grow(-2, -2);
    if (imgres == null) {
        imgres = img.getScaledInstance(rec.width, rec.height, Image.SCALE_SMOOTH);
    }
    g.drawImage(imgres, rec.x, rec.y, null);
}
 
Example 4
Source File: IOUtil.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Resize image to a max width or height image size.
 *
 * @param inputImage input image
 * @param max        max size
 * @return scaled image
 */
public static BufferedImage resizeImage(BufferedImage inputImage, int max) {
    int width = inputImage.getWidth();
    int height = inputImage.getHeight();
    int targetWidth;
    int targetHeight;
    if (width <= max && height <= max) {
        return inputImage;
    } else if (width > height) {
        targetWidth = max;
        targetHeight = targetWidth * height / width;
    } else {
        targetHeight = max;
        targetWidth = targetHeight * width / height;
    }
    Image scaledImage = inputImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
    BufferedImage targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
    targetImage.getGraphics().drawImage(scaledImage, 0, 0, null);
    return targetImage;
}
 
Example 5
Source File: Imager.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
public static void zoomImage(String src, Integer maxPicSize) throws Exception {
	File srcFile = new File(src);
	long fileSize = srcFile.length();
	String subfix = FileHelper.getFileSuffix(srcFile.getName());
	List<String> list = Arrays.asList( "jpg,jpeg,bmp,gif".split(",") ); // 这些格式支持有损压缩,png等不支持
	
	if (fileSize <= maxPicSize * 1024 || !list.contains(subfix.toLowerCase()))  { // 文件本身已小于size(K)时,不做缩放
		return;
	}
		
	Double rate = (maxPicSize * 1024.0) / fileSize; // 获取长宽缩放比例
	rate = Math.max(rate, 0.5);

	BufferedImage bufImg = ImageIO.read(srcFile);
	Image Itemp = bufImg.getScaledInstance(bufImg.getWidth(), bufImg.getHeight(), Image.SCALE_SMOOTH);

	AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(rate, rate), null);
	Itemp = ato.filter(bufImg, null);
	
	ImageIO.write((BufferedImage) Itemp, subfix, srcFile);
}
 
Example 6
Source File: HeatmapPanel.java    From Juicebox with MIT License 5 votes vote down vote up
public Image getThumbnailImage(MatrixZoomData zd0, MatrixZoomData ctrl0, int tw, int th, MatrixType displayOption,
                               NormalizationType observedNormalizationType, NormalizationType controlNormalizationType) {
    if (MatrixType.isPearsonType(displayOption) && hic.isPearsonsNotAvailableForFile(false)) {
    JOptionPane.showMessageDialog(this, "Pearson's matrix is not available at this resolution");
    return null;
  }

  int maxBinCountX = zd0.getXGridAxis().getBinCount();
  int maxBinCountY = zd0.getYGridAxis().getBinCount();

  int wh = Math.max(maxBinCountX, maxBinCountY);
  //if (wh > 1000) wh=1000; // this can happen with single resolution hic files - breaks thumbnail localization

  BufferedImage image = (BufferedImage) createImage(wh, wh);
  Graphics2D g = image.createGraphics();
  if (HiCGlobals.isDarkulaModeEnabled) {
    g.setColor(Color.darkGray);
    g.fillRect(0, 0, wh, wh);
  }

  boolean success = renderer.render(0,
      0,
      maxBinCountX,
      maxBinCountY,
      zd0,
      ctrl0,
      displayOption,
          observedNormalizationType,
          controlNormalizationType,
      hic.getExpectedValues(),
      hic.getExpectedControlValues(),
      g, false);

  if (!success) return null;

  return image.getScaledInstance(tw, th, Image.SCALE_REPLICATE);

}
 
Example 7
Source File: Compiler.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
private BufferedImage produceForegroundImageIcon(BufferedImage icon) {
  int imageWidth = icon.getWidth();
  // According to the adaptive icon documentation, both layers are 108x108dp but only the inner
  // 72x72dp appears in the masked viewport, so we shrink down the size of the image accordingly.
  double iconWidth = imageWidth * 72.0 / 108.0;
  // Round iconWidth value to even int for a centered png
  int intIconWidth = ((int)Math.round(iconWidth / 2) * 2);
  Image tmp = icon.getScaledInstance(intIconWidth, intIconWidth, Image.SCALE_SMOOTH);
  int marginWidth = ((imageWidth - intIconWidth) / 2);
  BufferedImage foregroundImageIcon = new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB);
  Graphics2D g2 = foregroundImageIcon.createGraphics();
  g2.drawImage(tmp, marginWidth, marginWidth, null);
  return foregroundImageIcon;
}
 
Example 8
Source File: ImageUtil.java    From util with Apache License 2.0 5 votes vote down vote up
/**
 * 图像切割(按指定起点坐标和宽高切割)
 * @param srcImageFile 源图像地址
 * @param result 切片后的图像地址
 * @param x 目标切片起点坐标X
 * @param y 目标切片起点坐标Y
 * @param width 目标切片宽度
 * @param height 目标切片高度
 */
public final static void cut(String srcImageFile, String result,
        int x, int y, int width, int height) {
    try {
        // 读取源图像
        BufferedImage bi = ImageIO.read(new File(srcImageFile));
        int srcWidth = bi.getHeight(); // 源图宽度
        int srcHeight = bi.getWidth(); // 源图高度
        if (srcWidth > 0 && srcHeight > 0) {
            Image image = bi.getScaledInstance(srcWidth, srcHeight,
                    Image.SCALE_DEFAULT);
            // 四个参数分别为图像起点坐标和宽高
            // 即: CropImageFilter(int x,int y,int width,int height)
            ImageFilter cropFilter = new CropImageFilter(x, y, width, height);
            Image img = Toolkit.getDefaultToolkit().createImage(
                    new FilteredImageSource(image.getSource(),
                            cropFilter));
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图
            g.dispose();
            // 输出为文件
            ImageIO.write(tag, "JPEG", new File(result));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 9
Source File: AipBodyAnalysis.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
    Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
    BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2d = dimg.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();

    return dimg;
}
 
Example 10
Source File: ImageUtil.java    From xnx3 with Apache License 2.0 5 votes vote down vote up
/**
 * 后缀格式转换,读入 png、jpg、gif格式图片的 {@link BufferedImage} ,返回新生成的内存图像,可另行保存为png、jpg、gif等格式
 * @param bufferedImage
 * @return 新创建的 {@link BufferedImage}
 */
public static BufferedImage formatConversion(BufferedImage bufferedImage){
	 Image image = bufferedImage.getScaledInstance(bufferedImage.getWidth(),bufferedImage.getHeight(), Image.SCALE_DEFAULT);
     BufferedImage tag = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
     Graphics g = tag.getGraphics();
     g.drawImage(image, 0, 0, null); // 绘制新图
     g.dispose();
     return tag;
}
 
Example 11
Source File: GeneratePosterBuilder.java    From spring-boot-cookbook with Apache License 2.0 5 votes vote down vote up
public GeneratePosterBuilder addHeadImage(String headImageUrl) throws IOException {
        URL url = new URL(headImageUrl);
        BufferedImage headImage = ImageIO.read(url.openStream());
        int x = 470;
        int y = 520;
        int width = 190;
        int height = 190;


        Shape olcClip = graphics2D.getClip();
        Stroke oldStroke = graphics2D.getStroke();
        BasicStroke s = new BasicStroke(20f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        graphics2D.setStroke(s);
        Ellipse2D.Double shape = new Ellipse2D.Double(x, y, width, height);
        log.info("中心点的坐标:CenterX:{},CenterY:{}", shape.getCenterX(), shape.getCenterY());
        // graphics2D.fill(new Rectangle(templateWidth, templateWidth));

        graphics2D.setStroke(new BasicStroke(1f));
//        graphics2D.setColor(Color.WHITE);
        graphics2D.setColor(Color.green);

        graphics2D.draw(shape);

        graphics2D.clip(shape);
        headImage.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
        graphics2D.drawImage(headImage, x, y, null);
//        graphics2D.setColor(Color.WHITE);
//        shape = new Ellipse2D.Double(x, y, width - 1, height - 1);
//        graphics2D.drawOval(x, y, width, height);
//        graphics2D.draw(shape);
        graphics2D.setClip(olcClip);
        graphics2D.setStroke(oldStroke);
//        graphics2D.drawImage(headImage, x - width - 10, y, width, height, null);
        return this;
    }
 
Example 12
Source File: SwingXpraClient.java    From xpra-client with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onCursorUpdate(CursorPacket cursorPacket) {
	super.onCursorUpdate(cursorPacket);
	if(cursorPacket.isEmpty()) {
		return;
	}
	int width = cursorPacket.width;
	int height = cursorPacket.height;
	
	ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
   int[] nBits = {8, 8, 8, 8};
   int[] bOffs = {1, 2, 3, 0};
   ColorModel colorModel = new ComponentColorModel(cs, nBits, true, true,
                                        Transparency.TRANSLUCENT,
                                        DataBuffer.TYPE_BYTE);
   WritableRaster raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,
                                           width, height,
                                           width*4, 4,
                                           bOffs, null);
   
	BufferedImage img = new BufferedImage(colorModel, raster, true, null);
	img.getRaster().setDataElements(0, 0, width, height, cursorPacket.pixels);
	
	Toolkit toolkit = Toolkit.getDefaultToolkit();
	Dimension size = toolkit.getBestCursorSize(width, height);
	Point hotspot = new Point(cursorPacket.xHotspot, cursorPacket.yHotspot);
	Image outputImg = img;
	if(size.width != width || size.height != height) {
		outputImg = img.getScaledInstance(size.width, size.height, Image.SCALE_SMOOTH);
		hotspot.x = hotspot.x * size.width / width;
		hotspot.y = hotspot.y * size.height / height;
	}
	
	Cursor c = toolkit.createCustomCursor(outputImg, hotspot, "test");
	SwingFrame window = (SwingFrame) getWindow(1);
	window.window.setCursor(c);
}
 
Example 13
Source File: HeatmapPanel.java    From JuiceboxLegacy with MIT License 5 votes vote down vote up
public Image getThumbnailImage(MatrixZoomData zd0, MatrixZoomData ctrl0, int tw, int th, MatrixType displayOption,
                               NormalizationType normalizationType) {

    if (displayOption == MatrixType.PEARSON &&
            zd0.getPearsons(hic.getDataset().getExpectedValues(zd0.getZoom(), normalizationType)) == null) {
        JOptionPane.showMessageDialog(this, "Pearson's matrix is not available at this resolution");
        return null;

    }
    int maxBinCountX = zd0.getXGridAxis().getBinCount();
    int maxBinCountY = zd0.getYGridAxis().getBinCount();

    int wh = Math.max(maxBinCountX, maxBinCountY);
    if (wh > 1000) wh=1000; // this can happen with single resolution hic files

    BufferedImage image = (BufferedImage) createImage(wh, wh);
    Graphics2D g = image.createGraphics();
    boolean success = renderer.render(0,
            0,
            maxBinCountX,
            maxBinCountY,
            zd0,
            ctrl0,
            displayOption,
            normalizationType,
            hic.getDataset().getExpectedValues(zd0.getZoom(), normalizationType),
            g);

    if (!success) return null;

    return image.getScaledInstance(tw, th, Image.SCALE_REPLICATE);

}
 
Example 14
Source File: DockManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private MyDragSession(MouseEvent me, @Nonnull DockableContent content) {
  myWindow = JWindowPopupFactory.getInstance().create(null);
  myContent = content;

  Image previewImage = content.getPreviewImage();

  double requiredSize = 220;

  double width = previewImage.getWidth(null);
  double height = previewImage.getHeight(null);

  double ratio;
  if (width > height) {
    ratio = requiredSize / width;
  }
  else {
    ratio = requiredSize / height;
  }

  BufferedImage buffer = UIUtil.createImage(myWindow, (int)width, (int)height, BufferedImage.TYPE_INT_ARGB);
  buffer.createGraphics().drawImage(previewImage, 0, 0, (int)width, (int)height, null);

  myDefaultDragImage = buffer.getScaledInstance((int)(width * ratio), (int)(height * ratio), Image.SCALE_SMOOTH);
  myDragImage = myDefaultDragImage;

  myWindow.getContentPane().setLayout(new BorderLayout());
  myImageContainer = new JLabel(IconUtil.createImageIcon(myDragImage));
  myImageContainer.setBorder(new LineBorder(Color.lightGray));
  myWindow.getContentPane().add(myImageContainer, BorderLayout.CENTER);

  setLocationFrom(me);

  myWindow.setVisible(true);

  WindowManagerEx.getInstanceEx().setAlphaModeEnabled(myWindow, true);
  WindowManagerEx.getInstanceEx().setAlphaModeRatio(myWindow, 0.1f);
  myWindow.getRootPane().putClientProperty("Window.shadow", Boolean.FALSE);
}
 
Example 15
Source File: ImageUtils.java    From AndroidDrawableFactory with MIT License 5 votes vote down vote up
public static Image resizeImage(BufferedImage bImg, int newWidth, int newHeight) throws FileNotFoundException, IOException
{
	
	double ratio = getAspectRatio(bImg, newWidth, newHeight);
	newWidth = (int) (bImg.getWidth(null) * ratio);
	newHeight = (int) (bImg.getHeight(null) * ratio);
	
	Image resizedImage = bImg.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
	
	return resizedImage;
}
 
Example 16
Source File: IconizedList.java    From dsworkbench with Apache License 2.0 5 votes vote down vote up
public IconizedList(String pResourcePath) {
    try {
        BufferedImage b = ImageIO.read(IconizedList.class.getResource(pResourcePath));
        iconImage = b.getScaledInstance(80, 80, BufferedImage.SCALE_SMOOTH);
    } catch (Exception ignored) {
    }
}
 
Example 17
Source File: ImgUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
/** 
 * 缩放图像(按高度和宽度缩放) 
 * @param src 源图像文件地址 
 * @param tar 缩放后的图像地址 
 * @param format 格式
 * @param height 缩放后的高度 
 * @param width 缩放后的宽度 
 * @param fill 比例不对时是否需要补白:true为补白; false为不补白; 
 */ 
public static void scale(File src, File tar, String format, int width, int height, boolean fill) { 
	long fr = System.currentTimeMillis(); 
    try { 
        double ratio = 0.0; // 缩放比例 
        BufferedImage bi = ImageIO.read(src); 
        Image itemp = bi.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH); 
        // 计算比例 
        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); 
        if (fill) {//补白 
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
            Graphics2D g = image.createGraphics(); 
            g.setColor(Color.white); 
            g.fillRect(0, 0, width, height); 
            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; 
        } 
        File dir = tar.getParentFile(); 
        if(!dir.exists()){ 
        	dir.mkdirs(); 
        } 
       // ImageIO.write((BufferedImage) itemp, "JPEG", tar); 
        ImageIO.write((BufferedImage)itemp, format, tar); 
    } catch (IOException e) { 
        e.printStackTrace(); 
    } 
    log.warn("[压缩图片][耗时:{}][source:{}][target:{}]",(System.currentTimeMillis()-fr), src, tar); 
}
 
Example 18
Source File: ImgQrTool.java    From MeetingFilm with Apache License 2.0 5 votes vote down vote up
/**
 * 把传入的原始图像按高度和宽度进行缩放,生成符合要求的图标
 *
 * @param srcImageFile 源文件地址
 * @param height       目标高度
 * @param width        目标宽度
 * @param hasFiller    比例不对时是否需要补白:true为补白; false为不补白;
 * @throws IOException
 */
private static BufferedImage scale(String srcImageFile, int height, int width, boolean hasFiller)
        throws IOException {
    double ratio = 0.0; // 缩放比例
    File file = new File(srcImageFile);
    BufferedImage srcImage = ImageIO.read(file);
    Image destImage = srcImage.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
    // 计算比例
    if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {
        if (srcImage.getHeight() > srcImage.getWidth()) {
            ratio = (new Integer(height)).doubleValue() / srcImage.getHeight();
        } else {
            ratio = (new Integer(width)).doubleValue() / srcImage.getWidth();
        }
        AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
        destImage = op.filter(srcImage, null);
    }
    if (hasFiller) {// 补白
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphic = image.createGraphics();
        graphic.setColor(Color.white);
        graphic.fillRect(0, 0, width, height);
        if (width == destImage.getWidth(null))
            graphic.drawImage(destImage, 0, (height - destImage.getHeight(null)) / 2, destImage.getWidth(null),
                    destImage.getHeight(null), Color.white, null);
        else
            graphic.drawImage(destImage, (width - destImage.getWidth(null)) / 2, 0, destImage.getWidth(null),
                    destImage.getHeight(null), Color.white, null);
        graphic.dispose();
        destImage = image;
    }
    return (BufferedImage) destImage;
}
 
Example 19
Source File: Screencaster.java    From termd with Apache License 2.0 4 votes vote down vote up
private void broadcast() {
  if (interrupted) {
    conn.close();
    return;
  }
  BufferedImage capture = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
  Vector size = conn.size();
  Image temp = capture.getScaledInstance(size.x(), size.y(), Image.SCALE_SMOOTH);
  BufferedImage scaled = new BufferedImage(size.x(), size.y(), BufferedImage.TYPE_INT_ARGB);
  Graphics2D g2d = scaled.createGraphics();
  g2d.drawImage(temp, 0, 0, null);
  g2d.dispose();
  StringBuilder sb = new StringBuilder();
  for (int y = 0; y < size.y(); y++) {
    sb.append("\033[").append(y + 1).append(";1H");
    for (int x = 0; x < size.x(); x++) {
      Color pixel = new Color(scaled.getRGB(x, y));
      int r = pixel.getRed();
      int g = pixel.getGreen();
      int b = pixel.getBlue();
      double grey = (r + g + b) / 3.0;
      if (grey < 51) {
        sb.append('\u2588');
      } else if (grey < 102) {
        sb.append('\u2593');
      } else if (grey < 153) {
        sb.append('\u2592');
      } else if (grey < 204) {
        sb.append('\u2591');
      } else {
        sb.append(' ');
      }
    }
  }
  conn.write(sb.toString());
  conn.schedule(new Runnable() {
    @Override
    public void run() {
      broadcast();
    }
  }, 100, TimeUnit.SECONDS);
}
 
Example 20
Source File: Images.java    From hermes with Apache License 2.0 4 votes vote down vote up
/**
 * Resize an image
 * 
 * @param originalImage
 *            The image file
 * @param to
 *            The destination file
 * @param w
 *            The new width (or -1 to proportionally resize) or the maxWidth
 *            if keepRatio is true
 * @param h
 *            The new height (or -1 to proportionally resize) or the
 *            maxHeight if keepRatio is true
 * @param keepRatio
 *            : if true, resize will keep the original image ratio and use w
 *            and h as max dimensions
 */
public static void resize(File originalImage, File to, int w, int h, boolean keepRatio) {
	try {
		BufferedImage source = ImageIO.read(originalImage);
		int owidth = source.getWidth();
		int oheight = source.getHeight();
		double ratio = (double) owidth / oheight;

		int maxWidth = w;
		int maxHeight = h;

		if (w < 0 && h < 0) {
			w = owidth;
			h = oheight;
		}
		if (w < 0 && h > 0) {
			w = (int) (h * ratio);
		}
		if (w > 0 && h < 0) {
			h = (int) (w / ratio);
		}

		if (keepRatio) {
			h = (int) (w / ratio);
			if (h > maxHeight) {
				h = maxHeight;
				w = (int) (h * ratio);
			}
			if (w > maxWidth) {
				w = maxWidth;
				h = (int) (w / ratio);
			}
		}

		String mimeType = "image/jpeg";
		if (to.getName().endsWith(".png")) {
			mimeType = "image/png";
		}
		if (to.getName().endsWith(".gif")) {
			mimeType = "image/gif";
		}
		// out
		BufferedImage dest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Image srcSized = source.getScaledInstance(w, h, Image.SCALE_SMOOTH);
		Graphics graphics = dest.getGraphics();
		graphics.setColor(Color.WHITE);
		graphics.fillRect(0, 0, w, h);
		graphics.drawImage(srcSized, 0, 0, null);

		ImageWriter writer = ImageIO.getImageWritersByMIMEType(mimeType).next();
		ImageWriteParam params = writer.getDefaultWriteParam();
		FileImageOutputStream toFs = new FileImageOutputStream(to);
		writer.setOutput(toFs);
		IIOImage image = new IIOImage(dest, null, null);
		writer.write(null, image, params);
		toFs.flush();
		toFs.close();

	} catch (Exception e) {
		throw new RuntimeException(e);
	}

}