java 等比例缩放算法公式
java 实现对图片进行指定的缩小或放大

2010-02-02java 实现对图片进行指定的缩小或放大文章分类:Java编程package common.util;import java.awt.Color;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Rectangle;import java.awt.RenderingHints;import java.awt.geom.AffineTransform;import java.awt.image.BufferedImage;import java.awt.image.ColorModel;import java.awt.image.WritableRaster;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import javax.imageio.ImageIO;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;/*** 图片工具类,完成图片的截取** @author inc062977**/public class AlterUploadImage {/*** 实现图像的等比缩放* @param source* @param targetW* @param targetH* @return*/private static BufferedImage resize(BufferedImage source, int targetW,int targetH) {// targetW,targetH分别表示目标长和宽int type = source.getType();BufferedImage target = null;double sx = (double) targetW / source.getWidth();double sy = (double) targetH / source.getHeight();// 这里想实现在targetW,targetH范围内实现等比缩放。
java项目实现图片等比缩放

java项⽬实现图⽚等⽐缩放本⽂实例为⼤家分享了java项⽬实现图⽚等⽐缩放的具体代码,供⼤家参考,具体内容如下package common;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import javax.imageio.ImageIO;public class ImageCompressionTask implements Runnable{private InputStream is;private String fileName;private int width;private int height;/*** 初始化参数* @param is 图⽚输⼊流* @param file 图⽚* @param fileName 图⽚名称* @param width ⾼* @param height 宽*/public ImageCompressionTask(InputStream is,String fileName,int width,int height) {this.is=is;this.fileName=fileName;this.width=width;this.height=height;}public void run() {// TODO Auto-generated method stubtry{pressPic();}catch(Exception e){System.out.println("⽂件压缩失败"+e);}}private String compressPic() throws Exception{String path = "E:\ ie\\";//新图⽚存放路径String urlPath = path + fileName;BufferedImage buffImage;FileOutputStream output=null;BufferedImage compressPic=null;try {String imagetype = "";if(stIndexOf(".") != -1){imagetype = fileName.substring(stIndexOf(".") + 1).toLowerCase();}imagetype = imagetype.toLowerCase(); //⽂件后缀名output=new FileOutputStream(urlPath);buffImage=ImageIO.read(is);//图⽚缩放compressPic=compressPicMin(buffImage,width,height);//输出图⽚ImageIO.write(compressPic, imagetype, output);} finally {if(output!=null){try{output.close();}catch(IOException e){e.getStackTrace();}}if(is!=null){is.close();}}return fileName;}/*** 图⽚等⽐缩放*@param image 图⽚输⼊缓存流*@param outputWidth 图⽚压缩到的宽*@param outputHeight 图⽚压缩到的⾼*@return BufferedImage* */private BufferedImage compressPicMin(BufferedImage image,int outputWidth, int outputHeight) {// TODO Auto-generated method stubif(image==null){return null;}//如果图⽚本⾝的宽和⾼均⼩于要压缩到的宽和⾼,则不压缩直接返回if(outputWidth>image.getWidth(null)&&outputHeight>image.getHeight(null)){return image;}int newWidth;int newHeight;//宽和⾼等⽐缩放的率double rate1=(double)image.getWidth(null)/(double)outputWidth;double rate2=(double)image.getHeight(null)/(double)outputHeight;//控制缩放⼤⼩double rate=rate1<rate2 ? rate1:rate2;newWidth=(int) (image.getWidth(null)/rate);newHeight=(int) (image.getHeight(null)/rate);BufferedImage newImage=new BufferedImage(newWidth, newHeight,BufferedImage.TYPE_INT_RGB);newImage.createGraphics().drawImage(image.getScaledInstance(newWidth, outputHeight, Image.SCALE_SMOOTH), 0, 0, null); return newImage;}public int getWidth() {return width;}public void setWidth(int width) {this.width = width;}public int getHeight() {return height;}public void setHeight(int height) {this.height = height;}}创建ImageTest写⼀个main()package test1;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.SynchronousQueue;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;import common.ImageCompressionTask;public class ImageTest {public static void main(String[] args){String imgName = System.currentTimeMillis() + "_" + ((int) (Math.random() * 900) + 100) + "." + "jpg";File f=new File("E:\ ie\ xx.jpg");try {InputStream input = new FileInputStream(f);ImageCompressionTask r=new ImageCompressionTask(input, imgName, 520, 320);/** ⽅法⼀:*Thread thread1 = new Thread(r);thread1.start(); // 启动线程*//** ⽅法⼆:使⽤ThreadPoolExecutor创建线程池,并不提倡我们直接使⽤ThreadPoolExecutor**//* ThreadPoolExecutor executor = new ThreadPoolExecutor(5, //核⼼池的⼤⼩(即线程池中的线程数⽬⼤于这个参数时,提交的任务会被放进任务缓存队列)10, //线程池最⼤能容忍的线程数200, //线程存活时间LISECONDS, //参数keepAliveTime的时间单位new ArrayBlockingQueue<Runnable>(5) //任务缓存队列,⽤来存放等待执⾏的任务);executor.execute(r);*//** ⽅法三:并不提倡我们直接使⽤ThreadPoolExecutor,⽽是使⽤Executors类中提供的⼏个静态⽅法来创建线程池 * 以下是三个静态⽅法* Executors.newCachedThreadPool(); //创建⼀个缓冲池,缓冲池容量⼤⼩为Integer.MAX_VALUE* Executors.newSingleThreadExecutor(); //创建容量为1的缓冲池* Executors.newFixedThreadPool(int); //创建固定容量⼤⼩的缓冲池*/newCachedThreadPool().execute(r);//newSingleThreadExecutor().execute(r);//newFixedThreadPool(10).execute(r);System.out.println("图⽚上传成功");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*静态⽅法的具体实现* Executors.newCachedThreadPool()* 创建⼀个缓冲池,缓冲池容量⼤⼩为Integer.MAX_VALUE*/public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());}/*静态⽅法的具体实现* Executors.newSingleThreadExecutor()* 创建容量为1的缓冲池*/public static ExecutorService newSingleThreadExecutor() {return new ThreadPoolExecutor(1, 1,0L, LISECONDS,new LinkedBlockingQueue<Runnable>());}/*静态⽅法的具体实现* Executors.newFixedThreadPool(int)* 创建固定容量⼤⼩的缓冲池*/public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, LISECONDS,new LinkedBlockingQueue<Runnable>());}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
图片等比例缩小算法

图片等比例缩放算法
在许多语言中,都希望图片可以等比例缩小或者放大,但是仅仅依靠语言本身的方法,大多差强人意,所以在此提供一个所有语言通用的图片等比例缩小方法的算法。
这里以java 语言为例子
1.给两个值,设置你想要设置图片的宽和高;定义两个真正的宽和高;这里定义为double 类型
double setWidth,setHeight;
double width,height;
2.获取图片的宽和高
double imageWidth=image.getIconWidth();
double imageHeight=image.getIconHeight();
3.写出算法
if(setWidth/imageWidth<=setHeight/imageHeight){
width=imageWidth*(setWidth/imageWidth);
height=imageHeight*(setWidth/imageWidth);
}else{
width=imageWidth*(setHeight/imageHeight);
height=y*(setHeight/imageHeight);
}
(1)如果设置为int,上面的if就会变成(0<=0)了
(2)算法确实很简单,我们一般取比例值较小的
4,将上面的所得的width,height转化为int型。
用JavaScript实现图片等比例缩放

把下面的函数放在页面中(任意位置都可以):function resizeimg(ImgD,iwidth,iheight) {var image=new Image();image.src=ImgD.src;if(image.width>0 && image.height>0){if(image.width/image.height>= iwidth/iheight){if(image.width>iwidth){ImgD.width=iwidth;ImgD.height=(image.height*iwidth)/image.width;}else{ImgD.width=image.width;ImgD.height=image.height;}ImgD.alt=image.width+"×"+image.height;}else{if(image.height>iheight){ImgD.height=iheight;ImgD.width=(image.width*iheight)/image.height;}else{ImgD.width=image.width;ImgD.height=image.height;}ImgD.alt=image.width+"×"+image.height;}ImgD.style.cursor= "pointer"; //改变鼠标指针ImgD.onclick = function() { window.open(this.src);} //点击打开大图片if (erAgent.toLowerCase().indexOf("ie") > -1) { //判断浏览器,如果是IE ImgD.title = "请使用鼠标滚轮缩放图片,点击图片可在新窗口打开";ImgD.onmousewheel = function img_zoom() //滚轮缩放{var zoom = parseInt(this.style.zoom, 10) || 100;zoom += event.wheelDelta / 12;if (zoom> 0)this.style.zoom = zoom + "%";return false;}} else { //如果不是IEImgD.title = "点击图片可在新窗口打开";}}}在需要实现等比缩放的图片上加上onload语句,图片装载时初始化大小。
java等比例缩放图片

缩放图像的基本原理是创建一个目标大小的画布,然后读取源图像,并将该图像绘制这个画布上。
为了使程序通用,源图像和缩放后的目标图像应用分别使用InputStream和OutputStream来表示,代码如下:public static void scaleImage(InputStream imgInputStream, OutputStream imgOutputStream, int scale){try{Image src = javax.imageio.ImageIO.read(imgInputStream);int width = ( int ) (src.getWidth( null ) * scale / 100.0 );int height = ( int ) (src.getHeight( null ) * scale / 100.0 );BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);bufferedImage.getGraphics().drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0 , 0 , null );JPEGImageEncoderencoder = JPEGCodec.createJPEGEncoder(imgOutputStream);encoder.encode( bufferedImage);}catch (IOException e){e.printStackTrace();}}其中scale参数表示缩放比例,1至100,当然,也可以大于100,那就是放大图像了。
但要注意,放得太大会失真的。
当然,也可以重构scaleImage方法,使其可以接收图像文件名,代码如下:public static void scaleImage(String imgSrc, String imgDist, int scale){try{File file = new File(imgSrc);if( ! file.exists()){return}InputStream is = new FileInputStream(file);OutputStream os = new FileOutputStream(imgDist);scaleImage(is, os, scale);is.close();os.close();}catch(Exception e){e.printStackTrace();}}下面的代码按15%缩放scaleImage( " E:\\pictures\\test.jpg " , " e:\\test1.jpg " , 15 );。
java等比缩小、放大图片尺寸

1<dependency> 2<groupId>net.coobird</groupId> 3<artifactId>thumbnailator</artifactId> 4<version>0.4.8</version> 5</dependency>
3.解 决 方 案
代码实现:
1 /* 2 * 对图片进行等比缩小或放大 3 * @attention: 4 * Thumbnails可以将修改后的图片转换成OutputStream、BufferedImage或者File 5 * @date: 2022/2/16 18:37 6 * @param: imgInputPath 原图片路径 7 * @param: imgOutputPath 图片输出路径 8 * 可以更改原图片的格式(比如:原图片是png格式,我们可以在让其生成的时候变成非png格式) 9 * @param: scale 图片比例 10* @return: boolean 成功、失败 11*/ 12public static boolean compressPicBySize(String imgInputPath, String imgOutputPath, float scale) { 13boolean flag = false; 14String imgStatus = (scale > 1) ? "放大" : "缩小"; 15try { 16Thumbnails.of(imgInputPath).scale(scale).toFile(imgOutputPath); 17// 成功 18flag = true; ("图片{}成功", imgStatus); 20} catch (IOException e) { 21e.printStackTrace(); 22log.error("图片{}失败:{}", imgStatus, e.getMessage()); 23} 24return flag; 25}
java处理图片按比例缩放功能

java处理图⽚按⽐例缩放功能java中的图⽚按⽐例缩放功能1. 按固定长宽进⾏缩放/** 图⽚缩放,w,h为缩放的⽬标宽度和⾼度* src为源⽂件⽬录,dest为缩放后保存⽬录*/public static void zoomImage(String src,String dest,int w,int h) throws Exception {double wr=0,hr=0;File srcFile = new File(src);File destFile = new File(dest);BufferedImage bufImg = ImageIO.read(srcFile); //读取图⽚Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);//设置缩放⽬标图⽚模板wr=w*1.0/bufImg.getWidth(); //获取缩放⽐例hr=h*1.0 / bufImg.getHeight();AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);Itemp = ato.filter(bufImg, null);try {ImageIO.write((BufferedImage) Itemp,dest.substring(stIndexOf(".")+1), destFile); //写⼊缩减后的图⽚} catch (Exception ex) {ex.printStackTrace();}}2. 按固定⽂件⼤⼩进⾏缩放/** 图⽚按⽐率缩放* size为⽂件⼤⼩*/public static void zoomImage(String src,String dest,Integer size) throws Exception {File srcFile = new File(src);File destFile = new File(dest);long fileSize = srcFile.length();if(fileSize < size * 1024) //⽂件⼤于size k时,才进⾏缩放,注意:size以K为单位return;Double rate = (size * 1024 * 0.5) / fileSize; // 获取长宽缩放⽐例BufferedImage bufImg = ImageIO.read(srcFile);Image Itemp = bufImg.getScaledInstance(bufImg.getWidth(), bufImg.getHeight(), bufImg.SCALE_SMOOTH);AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(rate, rate), null);Itemp = ato.filter(bufImg, null);try {ImageIO.write((BufferedImage) Itemp,dest.substring(stIndexOf(".")+1), destFile);} catch (Exception ex) {ex.printStackTrace();}}。
getscaledinstance的用法

getscaledinstance方法的用法getscaledinstance是Java中Image类的一个方法,用于获取按比例缩放后的图像实例。
该方法可以根据指定的宽度和高度,自动调整图像的大小,保持原始图像的宽高比。
方法原型public static Image getScaledInstance(Image img, int width, int height, int hi nts)参数说明•img:要缩放的图像实例。
•width:目标图像的宽度。
•height:目标图像的高度。
•hints:缩放算法选项,可选值有:–Image.SCALE_DEFAULT:默认缩放算法。
–Image.SCALE_FAST:速度较快但质量较低的缩放算法。
–Image.SCALE_SMOOTH:速度较慢但质量较高的缩放算法。
–Image.SCALE_REPLICATE:使用复制像素的方式进行缩放。
–Image.SCALE_AREA_AVERAGING:使用平均区域值进行缩放。
返回值返回按比例缩放后的新图像实例。
使用示例下面是一个使用getscaledinstance方法进行图片缩放的示例代码:import java.awt.*;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;public class ImageScaler {public static void main(String[] args) {try {// 读取原始图像BufferedImage originalImage = ImageIO.read(new File("original.jpg "));// 调整图像大小int newWidth = 200;int newHeight = 200;Image scaledImage = originalImage.getScaledInstance(newWidth, newH eight, Image.SCALE_SMOOTH);// 创建缩放后的新图像实例BufferedImage scaledBufferedImage = new BufferedImage(newWidth, ne wHeight, BufferedImage.TYPE_INT_RGB);Graphics2D graphics2D = scaledBufferedImage.createGraphics();graphics2D.drawImage(scaledImage, 0, 0, null);graphics2D.dispose();// 将缩放后的图像保存到文件ImageIO.write(scaledBufferedImage, "jpg", new File("scaled.jpg")); } catch (IOException e) {e.printStackTrace();}}}在上述示例中,我们首先使用ImageIO.read方法读取原始图像文件,并将其存储在BufferedImage对象中。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
java 等比例缩放算法公式
等比例缩放是一种常用的图像处理算法,它可以将图像按照一定比例进行缩放,保持图像的形状不变。
在Java中,可以使用一些数学公式来实现等比例缩放算法。
等比例缩放算法的原理是通过对图像的每个像素进行计算,将其坐标按照一定比例进行缩放。
具体而言,对于原图像中的每个像素,我们可以通过以下公式来计算其在缩放后图像中的坐标:
新坐标 = 原坐标 * 缩放比例
其中,原坐标是原图像中的像素坐标,新坐标是缩放后图像中的像素坐标,缩放比例是缩放的比例。
在Java中,可以使用循环遍历的方式对图像的每个像素进行计算,然后将其放置在缩放后图像的对应位置上。
具体步骤如下:
1. 首先,读取原图像的宽度和高度,以及缩放比例。
2. 根据缩放比例,计算缩放后图像的宽度和高度。
3. 创建一个新的图像对象,用于存储缩放后的图像。
4. 使用嵌套循环遍历原图像的每个像素。
5. 对于每个像素,根据公式计算其在缩放后图像中的坐标。
6. 将原图像中的像素复制到缩放后图像的对应位置上。
7. 将缩放后的图像保存到指定的文件或内存中。
通过以上步骤,我们可以实现对图像的等比例缩放。
需要注意的是,在进行缩放时,为了保持图像的质量,可以使用一些插值算法对像素进行补充计算,以获得更加平滑的缩放效果。
常见的插值算法有最近邻插值、双线性插值和双三次插值等。
除了使用Java自带的图像处理库外,还可以使用一些第三方库来实现等比例缩放算法。
比如,可以使用OpenCV库来对图像进行缩放处理。
OpenCV是一个开源的计算机视觉库,提供了丰富的图像处理功能,包括图像缩放、旋转、滤波等。
等比例缩放是一种常用的图像处理算法,可以在保持图像形状不变的情况下对图像进行缩放。
在Java中,可以使用数学公式和图像处理库来实现等比例缩放算法。
通过对图像的每个像素进行计算,可以将图像按照一定比例进行缩放,从而获得更加满意的图像效果。