【转】JAVA生成缩略图

方法1:[第一种方法比后一种生成的缩略图要清晰]
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.io.InputStream;
import java.io.File;
import java.io.FileOutputStream;

public class Test {
 public 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范围内实现等比缩放。如果不需要等比缩放
 //则将下面的if else语句注释即可
 if(sx>sy)
 {
 sx = sy;
 targetW = (int)(sx * source.getWidth());
 }else{
 sy = sx;
 targetH = (int)(sy * source.getHeight());
 }
 if (type == BufferedImage.TYPE_CUSTOM) { //handmade
 ColorModel cm = source.getColorModel();
 WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
 boolean alphaPremultiplied = cm.isAlphaPremultiplied();
 target = new BufferedImage(cm, raster, alphaPremultiplied, null);
 } else
 target = new BufferedImage(targetW, targetH, type);
 Graphics2D g = target.createGraphics();
 //smoother than exlax:
 g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );
 g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
 g.dispose();
 return target;
 }
 public static void saveImageAsJpg (String fromFileStr,String saveToFileStr,int width,int hight)
 throws Exception {
 BufferedImage srcImage;
// String ex = fromFileStr.substring(fromFileStr.indexOf("."),fromFileStr.length());
 String imgType = "JPEG";
 if (fromFileStr.toLowerCase().endsWith(".png")) {
 imgType = "PNG";
 }
// System.out.println(ex);
 File saveFile=new File(saveToFileStr);
 File fromFile=new File(fromFileStr);
 srcImage = ImageIO.read(fromFile);
 if(width > 0 || hight > 0)
 {
 srcImage = resize(srcImage, width, hight);
 }
 ImageIO.write(srcImage, imgType, saveFile);

 }
 
 public static void main (String argv[]) {
 try{
 //参数1(from),参数2(to),参数3(宽),参数4(高)
 Test.saveImageAsJpg("E:/Document/My Pictures/3.gif","c:/6.gif",50,50);
 } catch(Exception e)
 {
 e.printStackTrace();
 }

 }
}

方法2:
import java.io.*;
 import java.util.*;
 import com.sun.image.codec.jpeg.*;
 import java.awt.image.*;
 import java.awt.*;
 import java.net.*;
 import java.applet.*;
 import java.sql.*;

//缩略图类,
//本java类能将jpg图片文件,进行等比或非等比的大小转换。
//具体使用方法
//s_pic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true))
 public class Tes {
 String InputDir; //输入图路径
 String OutputDir; //输出图路径
 String InputFileName; //输入图文件名
 String OutputFileName; //输出图文件名
 int OutputWidth = 80; //默认输出图片宽
 int OutputHeight = 80; //默认输出图片高
 int rate = 0;
 boolean proportion = true; //是否等比缩放标记(默认为等比缩放)

 public Tes() {
//初始化变量
 InputDir = "";
 OutputDir = "";
 InputFileName = "";
 OutputFileName = "";
 OutputWidth = 80;
 OutputHeight = 80;
 rate = 0;
 }

 public void setInputDir(String InputDir) {
 this.InputDir = InputDir;
 }

 public void setOutputDir(String OutputDir) {
 this.OutputDir = OutputDir;
 }

 public void setInputFileName(String InputFileName) {
 this.InputFileName = InputFileName;
 }

 public void setOutputFileName(String OutputFileName) {
 this.OutputFileName = OutputFileName;
 }

 public void setOutputWidth(int OutputWidth) {
 this.OutputWidth = OutputWidth;
 }

 public void setOutputHeight(int OutputHeight) {
 this.OutputHeight = OutputHeight;
 }

 public void setW_H(int width, int height) {
 this.OutputWidth = width;
 this.OutputHeight = height;
 }

 public String s_pic() {
 BufferedImage image;
 String NewFileName;
//建立输出文件对象
 File file = new File(OutputDir + OutputFileName);
 FileOutputStream tempout = null;
 try {
 tempout = new FileOutputStream(file);
 } catch (Exception ex) {
 System.out.println(ex.toString());
 }
 Image img = null;
 Toolkit tk = Toolkit.getDefaultToolkit();
 Applet app = new Applet();
 MediaTracker mt = new MediaTracker(app);
 try {
 img = tk.getImage(InputDir + InputFileName);
 mt.addImage(img, 0);
 mt.waitForID(0);
 } catch (Exception e) {
 e.printStackTrace();
 }

 if (img.getWidth(null) == -1) {
 System.out.println(" can't read,retry!" + "<BR>");
 return "no";
 } else {
 int new_w;
 int new_h;
 if (this.proportion == true) { //判断是否是等比缩放.
//为等比缩放计算输出的图片宽度及高度
 double rate1 = ((double) img.getWidth(null)) /
 (double) OutputWidth + 0.1;
 double rate2 = ((double) img.getHeight(null)) /
 (double) OutputHeight + 0.1;
 double rate = rate1 > rate2 ? rate1 : rate2;
 new_w = (int) (((double) img.getWidth(null)) / rate);
 new_h = (int) (((double) img.getHeight(null)) / rate);
 } else {
 new_w = OutputWidth; //输出的图片宽度
 new_h = OutputHeight; //输出的图片高度
 }
 BufferedImage buffImg = new BufferedImage(new_w, new_h,
 BufferedImage.TYPE_INT_RGB);

 Graphics g = buffImg.createGraphics();

 g.setColor(Color.white);
 g.fillRect(0, 0, new_w, new_h);

 g.drawImage(img, 0, 0, new_w, new_h, null);
 g.dispose();

 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(tempout);
 try {
 encoder.encode(buffImg);
 tempout.close();
 } catch (IOException ex) {
 System.out.println(ex.toString());
 }
 }
 return "ok";
 }

 public String s_pic(String InputDir, String OutputDir, String InputFileName,
 String OutputFileName) {
//输入图路径
 this.InputDir = InputDir;
//输出图路径
 this.OutputDir = OutputDir;
//输入图文件名
 this.InputFileName = InputFileName;
//输出图文件名
 this.OutputFileName = OutputFileName;
 return s_pic();
 }

 public String s_pic(String InputDir, String OutputDir, String InputFileName,
 String OutputFileName, int width, int height,
 boolean gp) {
//输入图路径
 this.InputDir = InputDir;
//输出图路径
 this.OutputDir = OutputDir;
//输入图文件名
 this.InputFileName = InputFileName;
//输出图文件名
 this.OutputFileName = OutputFileName;
//设置图片长宽
 setW_H(width, height);
//是否是等比缩放 标记
 this.proportion = gp;
 return s_pic();
 }

 public static void main(String[] a) {
//s_pic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度)
 Tes mypic = new Tes();
 System.out.println(
 mypic.s_pic("E:\\Document\\My Pictures\\",
 "E:\\Document\\My Pictures\\",
 "topbg-3.gif", "3.gif", 400, 400, true)
 );

 }
 }

3.jsp方式
java.io.*,java.awt.Image,java.awt.image.*,com.sun.image.codec.jpeg.*,

  try
    {
 java.io.File file = new java.io.File("E:\\Document\\My Pictures\\3.gif");
 String newurl="E:\\Document\\My Pictures\\32.gif"; //新的缩略图保存地址
 Image src = javax.imageio.ImageIO.read(file); //构造Image对象
 float tagsize=200;
 int old_w=src.getWidth(null); //得到源图宽
 int old_h=src.getHeight(null);
 int new_w=0;
 int new_h=0; //得到源图长
 int tempsize;
 float tempdouble;
 if(old_w>old_h){
 tempdouble=old_w/tagsize;
 }else{
 tempdouble=old_h/tagsize;
 }
 new_w=Math.round(old_w/tempdouble);
 new_h=Math.round(old_h/tempdouble);//计算新图长宽
 BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
 tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图
 FileOutputStream newimage=new FileOutputStream(newurl); //输出到文件流
 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
 encoder.encode(tag); //近JPEG编码
 newimage.close();

}catch (Exception e){

e.toString();

}
 

转载于:https://www.cnblogs.com/leic2000/archive/2008/12/31/1366191.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/379794.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

javascript写入_如何在JavaScript中写入HTML元素?

javascript写入写入HTML元素 (Writing into an HTML element) To write string/text into an HTML element, we use the following things: 要将字符串/文本写入HTML元素&#xff0c;我们使用以下内容&#xff1a; There must be an HTML element like paragraph, span, div e…

大话设计模式之设计模式遵循的七大原则

最近几年来&#xff0c;人们踊跃的提倡和使用设计模式&#xff0c;其根本原因就是为了实现代码的复用性&#xff0c;增加代码的可维护性。设计模式的实现遵循了一些原则&#xff0c;从而达到代码的复用性及增加可维护性的目的&#xff0c;设计模式对理解面向对象的三大特征有很…

IIC通信---EEPROM24C02---STMF4

IIC通信协议 IIC是同步半双工通信&#xff0c;一个数据线SDA和一个时钟SCL线&#xff0c;可以接受和发送数据。在CPU与被控IC之间、IC与IC之间进行双向传送。 空闲状态 IIC总线的SDA和SCL两条信号线同时处于高电平时&#xff0c;规定为总线的空闲状态。 起始信号 当SCL为高…

实训09.08:简单的算法练习

/*final 关键字 修饰的变量值 后期不可更改 相当于定义常量常量 &#xff1a;不可更改*/final int a 10;//a 20; 报错的值不可更改&#xff01;/*输入函数* */System.out.println("请输入数字&#xff1a;");Scanner scanner new Scanner(System.in);int b…

让自己闪亮

转载于:https://www.cnblogs.com/Gigabyte/archive/2009/01/03/you_can_shine.html

Java中的wait()和sleep()方法之间的区别

Java中的wait()和sleep()方法 (wait() and sleep() methods in Java) First, we will see how wait() method differs from sleep() method in Java? 首先&#xff0c;我们将看到wait()方法与Java中的sleep()方法有何不同&#xff1f; wait()方法 (wait() Method) This metho…

离线使用iPhone SDK文档的方法

在使用Xcode进行iPhone编程时&#xff0c;有时需要参考iPhone SDK的文档&#xff0c;不过每次ControlClick后&#xff0c;Xcode都会试图连接Internet&#xff0c;进行在线读取。有什么方法能够把资料下载到硬盘上进行离线阅读吗&#xff1f; 答案是肯定的。首先去Xcode的Prefer…

远程连接sql server 2000服务器的解决方案

远程连接sql server 2000服务器的解决方案2007-04-07 11:29远程连接sql server 2000服务器的解决方案   一 看ping 服务器IP能否ping通。   这个实际上是看和远程sql server 2000服务器的物理连接是否存在。如果不行&#xff0c;请检查网络&#xff0c;查看配置&#xff0c…

实训09.10:HTML简单表格设计

<!DOCTYPE html> <html><head><meta charset"UTF-8"><title>燕雨简历</title></head><body><table border"" cellspacing"" cellpadding"" width"400px" height"6…

LCD显示实验----STM32f4--HAL

步骤 LCD初始化 LCD_Init(); //LCD初始化此函数在lcd.c文件里面 2. 设置LCD背景颜色 LCD_Clear(WHITE);此函数在lcd.c文件里面 3. 设置字体颜色 POINT_COLORRED; 写入要显示的字体 LCD_ShowString(10,80,240,24,24,"LTDC TEST");LCD_ShowSt…

JavaScript | 使用提示从用户输入值

Example 1) Input name and print 示例1)输入名称和打印 Code (JS & HTML): 代码(JS和HTML)&#xff1a; <!DOCTYPE html><HTML><HEAD><SCRIPT>var name prompt("Enter Your name:");var msg "Welcome "name;//alert(msg)…

一个游戏程序员的学习资料 (zz)

一个游戏程序员的学习资料//z 2012-4-19 14:39:51 PM IS2120CSDN想起写这篇文章是在看侯杰先生的《深入浅出MFC》时, 突然觉得自己在大学这几年关于游戏编程方面还算是有些心得&#xff0c;因此写出这篇小文,介绍我眼中的游戏程序 员的书单与源代码参考。一则是作为自己今后两年…

项目管理中工作分解结构模型(WBSM)的应用

摘要 本文根据工作分解结构(WBS)的工作特点&#xff0c;运用系统工程的思想理论方法&#xff0c;构建了工作分解结构模型&#xff0c;并提出了模型算法;该模型方法的建立使得WBS工作更加简单可靠、思路清晰、基于更加可靠的科学基础之上。 1、工作分解结构模型(WBSM)方法工作程…

实训09.11:java重点内容介绍

package test;/** * OP:面向对象的简称* 类&#xff1a;同一特征的属性* * 类的定义&#xff1a;具有相同特征和行为的事物的抽象。&#xff08;不具体化&#xff09;* 对象&#xff08;实例对象&#xff09;&#xff1a;具体真实存在的实例。* 类是对象的实例&#xff1a;* *…

SPI通信原理---STM32F4--HAL

SPI接口原理 SPI是一种高速全双工同步通信&#xff0c;在芯片管脚上占用四根线&#xff0c;主要应用在EEPROM、FLASH、实时时钟、AD转换器&#xff0c;还有数字信号处理器和数字信号解码器之间。 SPI接口使用4根线通信。 MISO&#xff1a;主设备数据输入&#xff0c;从设备数…

Linux 引导管理器 grub2 使用简介

转自&#xff1a;杜昌彬的空间 首先向其致敬&#xff01;有改动。 grub是Linux系统即其他类unix系统的主流bootloder&#xff0c;由于grub原来版本的设计存在很大缺陷&#xff0c;与以前的grub很不相同&#xff0c;其使用和配置也发生很大变化。现在很多Linux发行版本都使用了…

pata1015_ATA / PATA的完整形式是什么?

pata1015ATA / PATA&#xff1a;高级技术附件/并行高级技术附件 (ATA/PATA: Advanced Technology Attachment/Parallel Advanced Technology Attachment) ATA is an abbreviation of Advanced Technology Attachment. ATA has existed for a long time with the name PATA. Whe…

产品

总结一下&#xff1a;  1、核心功能要做透&#xff0c;做的人家追不上&#xff0c;自己的优势要尽量的发挥&#xff1b;  2、产品口碑要建立&#xff0c;要关注高端用户&#xff0c;要调整自己心态&#xff1b;  3、敏捷、快&#xff0c;产品迭代要快&#xff0c;快速实现…

FreeRTOS在STM32F429上移植

准备工作 FreeRTOS系统源码基础工程&#xff0c;这里我们用跑马灯实验 1.在工程里面添加FreeRTOS源码 在工程里面新建一个名为FreeROTS的文件夹 将FreeRTOS源码添加到这个文件夹里面 protable里面只需留下Keil、MemMang、RVDS文件夹 2、向工程分组中添加文件 FreeRTOS_C…

C++中的指针与引用(转)

原文地址&#xff1a;http://www.cnblogs.com/skynet/archive/2010/09/22/1832911.html写在前面 指针和引用形式上很好区别&#xff0c;但是他们似乎有相同的功能,都能够直接引用对象&#xff0c;对其进行直接的操作。但是什么时候使用指针&#xff1f;什么时候使用引用呢&…