当前位置: 代码迷 >> J2SE >> 请教一个缩小并保存image对象的有关问题
  详细解决方案

请教一个缩小并保存image对象的有关问题

热度:13   发布时间:2016-04-24 00:28:29.0
请问一个缩小并保存image对象的问题
我现有一jpg格式图像,想把它缩小了并重新保存 

 先读入 BufferedImage img = ImageIO.read(filename);

   
然后 
  int syswidth = 200;
  int sysheight = 150;  
  Image simg = img.getScaledInstance(sysheight, syswidth,  
BufferedImage.SCALE_DEFAULT);  

  请问如何写到硬盘上去呢,或者能换个方法缩小

  ImageIo.write是不行了, 因为它需要的参数是BufferedImage, 而我得到的是Image型 


------解决方案--------------------
假设宽度比例为sx,高度比例为sy,double型
Java code
BufferedImage target = new BufferedImage(syswidth,sysheight,BufferedImage.TYPE_3BYTE_BGR); AffineTransform transform = new AffineTransform();transform.setToScale(sx,sy);//操作AffineTransformOp op = new AffineTransformOp(transform,null); op.filter(source,target);
------解决方案--------------------
public static Icon getFixedBoundIcon(String filePath,int height,int width) throws Exception
{
double ratio = 0.0;
File file = new File(filePath);
if(!file.isFile())
{
throw new Exception(file+" is not image file error in getFixedBoundIcon!");
}
Icon ret = new ImageIcon(filePath);
BufferedImage bi = ImageIO.read(file);
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+fileType);
Image temp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio),null);
temp = op.filter(bi, null);
ImageIO.write((BufferedImage)temp, "jpg", zoomFile);
ret = new ImageIcon(zoomFile.getPath());
}
return ret;
}
------解决方案--------------------
HTML code
http://blog.csdn.net/fancyerII/archive/2010/08/25/5837991.aspx
  相关解决方案