java图片等比例_java图片等比例缩放

该博客介绍了如何使用Java进行图片等比例缩放。通过引入相关jar包,利用ImageIO和JPEGCodec类,实现对图片的读取、缩放和保存。代码中设置最小宽度和高度,根据原图尺寸计算缩放比例,并使用SCALE_SMOOTH模式确保缩放后的图片质量。
摘要由CSDN通过智能技术生成

需要引入jar包

package com.gjw.imagetest;

import java.awt.Image;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;

import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImagePress

{

public static void main(String[] args)

{

try

{

File imgageio = new File("C:\\image\\big.jpg");

File imgageout = new File("C:\\image\\big22.png");

dosomething(imgageio,imgageout,50,50);

} catch (FileNotFoundException e)

{

e.printStackTrace();

}catch (IOException e)

{

e.printStackTrace();

}

}

public static boolean dosomething(File imagesrc,File imageout,int min_width,int min_height) throws IOException

{

if (!imagesrc.exists())

{

System.out.println("The original image does not exist!");

return false;

}

Image src = ImageIO.read(imagesrc);

if (src.getWidth(null)==-1)

{

System.out.println("image type problem!");

return false;

}else {

if (src.getWidth(null)>min_width || src.getHeight(null)>min_height)

{

double scale = 0.0;

double w_scale = 0.0;

double h_scale = 0.0;

if (src.getWidth(null)>min_width)

w_scale = min_width/(double)src.getWidth(null);

if (src.getHeight(null)>min_height)

h_scale = min_height/(double)src.getHeight(null);

scale=w_scale

System.out.println("scaling:="+scale);

if (scale<1)

{

int width = (int) (src.getWidth(null) * scale);

int height = (int) (src.getHeight(null) * scale);

System.out.println("w:"+width);

System.out.println("h:"+height);

/* java提供了4个缩放的微调选项

* image.SCALE_SMOOTH //平滑优先

* image.SCALE_FAST//速度优先

* image.SCALE_AREA_AVERAGING //区域均值

* image.SCALE_REPLICATE //像素复制型缩放

* image.SCALE_DEFAULT //默认缩放模式

* */

BufferedImage bufferedImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR);

bufferedImage.getGraphics().drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH),0, 0, null);

FileOutputStream out = new FileOutputStream(imageout);

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

encoder.encode( bufferedImage);

out.close();

System.out.println("photo compression success!");

return true;

}

}

System.out.println("Don't need to compress the images!");

return true;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值