java 等比例缩放算法公式
- 格式:docx
- 大小:3.35 KB
- 文档页数:2
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项⽬实现图⽚等⽐缩放的具体代码,供⼤家参考,具体内容如下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型。
把下面的函数放在页面中(任意位置都可以):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语句,图片装载时初始化大小。
缩放图像的基本原理是创建一个目标大小的画布,然后读取源图像,并将该图像绘制这个画布上。
为了使程序通用,源图像和缩放后的目标图像应用分别使用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处理图⽚按⽐例缩放功能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是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对象中。
java 按比例分配的公式按比例分配的问题在日常生活中非常常见,比如分蛋糕、分奖金等。
在数学和编程中,我们可以使用简单的比例计算公式来解决这些问题。
按比例分配的公式如下:假设我们有一个总量,比如100,然后我们有几个部分或者几个参与者,比如3个。
我们想按照2:1:1的比例来分配这100。
那么,我们可以这样计算:1. 首先,我们需要确定每个比例的权重。
在这个例子中,2+1+1=4。
2. 然后,我们将总量(100)除以权重(4)来得到每个比例的基准值:100/4 = 25。
3. 最后,我们根据每个比例的权重来计算每个部分的实际值:第一部分:2 25 = 50第二部分:1 25 = 25第三部分:1 25 = 25用Java代码实现这个计算非常简单:```javapublic class ProportionalDistribution {public static void main(String[] args) {int total = 100;int[] ratios = {2, 1, 1}; // 代表2:1:1的比例int sumOfRatios = ; // 计算权重总和int baseValue = total / sumOfRatios; // 计算基准值for (int i = 0; i < ; i++) {int ratio = ratios[i];int value = baseValue ratio; // 根据比例计算实际值 ("Part " + (i + 1) + ": " + value);}}}```运行上面的代码,你会得到以下输出:```makefile Part 1: 50 Part 2: 25 Part 3: 25 ```。
在Java中,可以使用各种数学和算术操作符来构建公式。
以下是一些常见的Java公式示例:简单运算:int result = 2 + 3; // 加法int result = 5 -2; // 减法int result = 4 * 6; // 乘法int result = 8 / 2; // 除法int result = 10 % 3; // 取模(求余)指数运算:double result = Math.pow(2, 3); // 2的3次方平方根和立方根:double result = Math.sqrt(25); // 平方根double result = Math.cbrt(27); // 立方根三角函数:double result = Math.sin(Math.PI / 2); // 正弦函数double result = Math.cos(Math.PI / 4); // 余弦函数double result = Math.tan(Math.PI / 6); // 正切函数对数和指数函数:double result = Math.log(10); // 自然对数double result = Math.log10(100); // 以10为底的对数double result = Math.exp(2); // e的指数函数绝对值和取整:int result = Math.abs(-10); // 绝对值double result = Math.ceil(3.14); // 向上取整double result = Math.floor(3.14); // 向下取整这只是一些常见的Java公式示例,Java还提供了许多其他数学函数和运算符,可以根据具体的需求和数学计算来选择适合的方法。
同时,还可以使用数学库或第三方库来扩展和增强Java中的数学功能。
java 等比例缩放算法公式
等比例缩放是一种常用的图像处理算法,它可以将图像按照一定比例进行缩放,保持图像的形状不变。
在Java中,可以使用一些数学公式来实现等比例缩放算法。
等比例缩放算法的原理是通过对图像的每个像素进行计算,将其坐标按照一定比例进行缩放。
具体而言,对于原图像中的每个像素,我们可以通过以下公式来计算其在缩放后图像中的坐标:
新坐标 = 原坐标 * 缩放比例
其中,原坐标是原图像中的像素坐标,新坐标是缩放后图像中的像素坐标,缩放比例是缩放的比例。
在Java中,可以使用循环遍历的方式对图像的每个像素进行计算,然后将其放置在缩放后图像的对应位置上。
具体步骤如下:
1. 首先,读取原图像的宽度和高度,以及缩放比例。
2. 根据缩放比例,计算缩放后图像的宽度和高度。
3. 创建一个新的图像对象,用于存储缩放后的图像。
4. 使用嵌套循环遍历原图像的每个像素。
5. 对于每个像素,根据公式计算其在缩放后图像中的坐标。
6. 将原图像中的像素复制到缩放后图像的对应位置上。
7. 将缩放后的图像保存到指定的文件或内存中。
通过以上步骤,我们可以实现对图像的等比例缩放。
需要注意的是,在进行缩放时,为了保持图像的质量,可以使用一些插值算法对像素进行补充计算,以获得更加平滑的缩放效果。
常见的插值算法有最近邻插值、双线性插值和双三次插值等。
除了使用Java自带的图像处理库外,还可以使用一些第三方库来实现等比例缩放算法。
比如,可以使用OpenCV库来对图像进行缩放处理。
OpenCV是一个开源的计算机视觉库,提供了丰富的图像处理功能,包括图像缩放、旋转、滤波等。
等比例缩放是一种常用的图像处理算法,可以在保持图像形状不变的情况下对图像进行缩放。
在Java中,可以使用数学公式和图像处理库来实现等比例缩放算法。
通过对图像的每个像素进行计算,可以将图像按照一定比例进行缩放,从而获得更加满意的图像效果。