用java的圖形用戶界面實現文件瀏覽功能(需要導包)
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Group;
import org.eclipse.wb.swt.SWTResourceManager;
public class TestShell {
protected Shell shell;
private Text text_file;
public static void main(String[] args) {
try {
TestShell window = new TestShell();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(500, 200);
shell.setText("解析WSDL");
text_file = new Text(shell, SWT.BORDER);
text_file.setBounds(80, 33, 290, 24);
//實現文件瀏覽功能
Button browseButton = new Button(shell,SWT.PUSH);
browseButton.setText("瀏覽...");
browseButton.setFont(SWTResourceManager.getFont("Tahoma", 12, SWT.NORMAL));
browseButton.setBounds(383, 33, 80, 24);
browseButton.addSelectionListener(new SelectionAdapter(){
/* (non-Javadoc)
* @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected(SelectionEvent e){
FileDialog dialog = new FileDialog (shell, SWT.OPEN);
dialog.setText("Source Folder Selection");
dialog.setFilterExtensions(new String[] {"*.txt","*.jpg","*.*"});
String filePath = dialog.open();
if(dialog!=null){
text_file.setText(filePath);
}
}
});
Button button_exe = new Button(shell, SWT.NONE);
button_exe.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
MessageBox msgbox = new MessageBox(shell,
SWT.ICON_QUESTION | SWT.OK);
msgbox.setText("提示");
String file = "";
file = text_file.getText();
if(file.equals("") || file == null){
msgbox.setMessage("WSDL文件不能為空");
msgbox.open();
return;
}else{
msgbox.setMessage("文件獲取到了!?。?);
System.out.println(file);
msgbox.open();
}
}
});
button_exe.setFont(SWTResourceManager.getFont("Tahoma", 12, SWT.NORMAL));
button_exe.setBounds(214, 133, 87, 23);
button_exe.setText("\u6267\u884C");
Group group = new Group(shell, SWT.NONE);
group.setBounds(10, 10, 472, 117);
Label label = new Label(group, SWT.NONE);
label.setBounds(10, 23, 105, 24);
label.setFont(SWTResourceManager.getFont("Tahoma", 12, SWT.NORMAL));
label.setText("源文件:");
}
}
Spring中的JDBCTemplate使用
數據庫準備:
創建數據庫

創建表:

Java代碼:
1、創建web 工程 springJdbcTemplate
2、添加Spring能力 在此需要將jdbc包也同時加入


3、配置上mysql的連接驅動(拷貝mysql驅動包,如果不拷貝報錯很詭異)
在applicationContext.xml中進行配置
在beans標簽中填寫
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref local="dataSource" />
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/myspringjdbcdb</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>root</value>
</property>
</bean>
4、創建包結構并且寫出類(每個類中可以沒內容)

5、每個類中的源代碼
UserDao.java

UserDaoImp.java

此項寫完填寫在applicationContext.xml中進行配置
在beans標簽中填寫

User.java

每個成員變量都寫上get和set方法
并且在此類中還要加入
此項寫完填寫在applicationContext.xml中進行配置
在beans標簽中填寫

測試類TestAction.java

打印出結果:

Remote Object Service
對于主流的Flex數據服務器,目前都支持AMF3/RemoteObject,今天我們就來談一談BlazeDS的遠程服務。
1. 編寫遠程服務類
編寫BlazeDS的Java遠程服務類有三個要求:
1) 所有被調用的方法必須是public;
2) 所有的編譯類必須能夠通過BlazeDS的classpath訪問得到;
3) 類必須是stateful/stateless的。
大家可以參考工程文件中的SimpleService.java。
2. 配置remoting-config.xml
Java服務類寫好后,還需要配置,BlazeDS的Remote Service也是在服務器端對應了一個配置文件:remoting-config.xml,配置好Remote Service 后,Flex在運行時才能找到相應的服務類并調用其方法。下面就是本工程的Remote Service配置文件。

第2~3行指定服務的ID和對應的類,第5~7行設置適配器(adapters)的ID和對應的類。第9~11行指定默認的通道(channels)及其參照,該通道是在 services-config.xml中定義的。適配器和通道可以設置多個,采用第一個優先的原則。前面這幾項設置適用于proxy-config.xml、remoting-config.xml和我們后面要講的 messaging-config.xml。
第13~18行設置的服務終端(destination),該屬性必須和RemoteObject組件的服務終端屬性一致。按照服務的種類,服務終端又可以分為代理服務終端、遠程服務終端和消息服務終端。上一次講述的代理服務終端,需要指定該終端的url,而這次我們講述的遠程服務終端,需要指定該目標的source和scope。source對應 RemoteObject要調用的遠程服務的全限定類名,不像FluorineFX,它不能在RemoteObject組件中指定。scope表示當前遠程服務的作用范圍,即遠程服務類是stateful還是stateless,有application、session和request三個選項。
注意:我們提倡在配置文件中設置,這樣更安全也方便后期維護。
3. 使用RemoteObjec組件
對于RemoteObjec組件,請參看
下面的Flex RemoteObject類參考相關內容。一句話,Flex的RemoteObject與后臺語言是無關的。在工程文件中的BasicRemoteObject.mxml,調用了SimpleService類的三個方法,當通過BlazeDS從J2EE服務器返回RemoteObjec時,Java數據被序列化成ActionScript數據。其中Java字符串對應ActionScript字符串,Java的數組列表對應ActionScript ArrayCollection。
Flex RemoteObject類參考
<mx:RemoteObject>標記允許使用AMF3訪問遠程服務類的方法,要知道在Flex中怎樣使用Flash Remoting訪問數據,應該先了解一下RemoteObject類。
要知道在Flex中怎樣使用Flash Remoting訪問數據,應該先了解一下RemoteObject類。
包 mx.rpc.remoting 類 public dynamic class RemoteObject
繼承 RemoteObject → AbstractService → Proxy → Object
子類 RemoteObject
一、<mx:RemoteObject>標記
它允許使用AMF3訪問遠程服務類的方法。
1. <mx:RemoteObject>允許的標記屬性有:
1
2
3
4
5
6
7
8
9
10
11
12
13 |
< mx:RemoteObject
Properties
concurrency = "multiple|single|last"
destination = "No default."
id = "No default."
endpoint = "No default."
showBusyCursor = "false|true"
source = "No default." (currently, Macromedia ColdFusion only)
makeObjectsBindable = "false|true"
事件
fault = "No default."
result = "No default."
/>
|
2. <mx:RemoteObject>標記可以包含多個 <mx:method> 標記,<mx:method>允許的標記屬性有:
1
2
3
4
5
6
7
8
9 |
< mx:method
Properties
concurrency = "multiple|single|last"
name = "No default, required."
makeObjectsBindable = "false|true"
事件
fault = "No default."
result = "No default."
/>
|
3. <mx:RemoteObject>標記可以也只能包含一個<mx:arguments> 子標記,該子標記是一個序列數組對象。
二、公有屬性
1. concurrency : String
表示對同一服務怎樣進行多次調用。類似于XMLConnector/WebServiceConnector/RemotingConnector的multipleSimultaneousAllowed屬性。它的默認值為multiple,允許下列值:
- Multiple:同一時間可以執行多個請求。已有的請求不會被取消;
- Single:同一時間調用只能執行一個請求,多個請求會報錯;
- Last:最后一次請求會覆蓋已有的請求。
2. endpoint: String
允許開發人員快速為RemoteObject destination(目標)指定endpoint(端點)。而該destination既沒有在編譯時,也沒有在用代碼新建ChannelSet(通道集)時參照services-config.xml。如果設定了該屬性,它會覆蓋已有的ChannelSet。
如果endpoint 的url 以“https”開關,將使用 SecureAMFChannel, 否則使用普通的AMFChannel。{server.name}和{server.port}標記,可以用在endpoint的url中,表明Channel應該使用用來加載SWF文件的服務名稱和端口。
3. showBusyCursor:Boolean
表示服務正在執行時是否顯示一個表示忙碌的鼠標指針。
三、公有方法
1. RemoteObject () 構造方法
創建一個新的RemoteObject對象。
參數
destination:String (默認為 null) —RemoteObject 的destination屬性必須匹配 services-config.xml 中的destination的ID屬性值。
2. initialized ()
public function initialized(document:Object, id:String):void
只要設定RemoteObject標記就會通過MXML編譯器自動調用該方法。如果使用ActionScrip新建RemoteObject實例,則可以自行調用該方法,這對驗證其參數很有用。
參數
- document:Object —RemoteObject 所在的MXML文檔
- id:String —RemoteObjec在上述文檔中的ID
在Flex中使用ActionScript,其實和在網頁中使用Javascript等腳本文件類似,主要有三種方式。
Flex的核心是MXML和ActionScript。MXML是用于為Flex應用程序進行用戶界面組件布局,它屬于表示層,最終要編輯成ActionScript 并生成ActionScript 類文件在Flash Player上運行。如果你是個Java開發者就很好理解這一點,MXML 就好比是JSP/Struts/JSF,它們最終都會編輯成Java類文件并在具備Java虛擬機環境的瀏覽器上運行。所以說,Flex 最核心的還是ActionScript 。在Flex中,ActionScript是 類庫的方式出現的,該類庫包含組件 (容器和控件)、管理器類、數據服務類和所有其他功能的類。本文將談一談在Flex中使用ActionScript的方法。
其實和在網頁中使用Javascript等腳本文件類似,主要有三種方式。
1. 內聯方式
這種方式直接將AS方法作為事件的屬性值,當然這種方法一般只有一行,相對簡單。如果要給方法傳遞對數,這種方法就不可取了。
1
2
3
4
5
6
7
8
9
10
11
12
13 |
<? xml version = "1.0" encoding = "utf-8" ?>
< mx:Application xmlns:mx = "http://www.adobe.com/2006/mxml" layout = "vertical" >
< mx:Button label = "Say Hello" click = "sayHello('Flying')" />
< mx:Script >
<![CDATA[
import mx.controls.Alert;
private function sayHello(param_name:String):void {
Alert.show("Hello, "+param_name);
}
]]>
</ mx:Script >
</ mx:Application >
|
2. 級聯方式
這種方式將AS方法放入<mx:Script></mx:Script>代碼塊中,然后將方法作為事件的屬性值,并可以在調用方法時傳遞參數,從而做到了AS方法在一個文件中的重用。
1
2
3
4
5
6 |
<? xml version = "1.0" encoding = "utf-8" ?>
< mx:Application xmlns:mx = "http://www.adobe.com/2006/mxml" layout = "vertical" >
< mx:Script source = "myFunction.as" />
< mx:Button label = "Say Hello" click = "sayHello('Flying');" />
</ mx:Application >
|
3. 外聯方式
1
2
3
4
5 |
mx.controls.Alert;
private function sayHello(param_name: String ): void {
mx.controls.Alert.show( "Hello, " +param_name);
}
|
上述方式為AS方法單獨新建一個as文件,然后設置該方法為被調用文件的Script元素的source屬性值,并可以在調用方法時傳遞參數,此文件可以在多個文件調用,從而實現了AS方法在多個文件中的重用。
Flex跳轉到JSP或者其他非Flex頁面
Html代碼
var url:String="http://"+URLUtil.getServerNameWithPort(Application.application.url)+"/DZDJ/index.jsp?id=" + 1;
ExternalInterface.call('window.open',url,'_top');
_top是可變的,_top表示在當前頁面打開,關閉遠頁面。
導入類:
import flash.net.URLRequest;
import flash.net.navigateToURL;
關閉當前瀏覽器:
var url:URLRequest = new URLRequest("javascript:window.close()");
navigateToURL(url,"_top");
(注意:要在服務器上測試,否則會報安全沙箱沖突);
在瀏覽器上跳轉頁面
navigateToURL(new URLRequest("http://www.baidu.com"),"_top");
打開一個新的瀏覽器:
var request:URLRequest = new URLRequest("http://www.baidu.com/);
navigateToURL(request);
Flex跳轉到Flex
FLEX和JSP不一樣,沒有所謂的這個頁面跳轉到另外的一個頁面。一般都是用ViewStack進行頁面切換,其他模塊就需要loadmoudle進行函數設置了。
<mx:ViewStack x="0" y="0" id="viewstack1" width="619" height="700">
<mx:Canvas id="View1" width="100%" height="100%">
<mx:Button label="View2 " click="viewstack1.selectedChild=View2"/>
</mx:Canvas>
<mx:Canvas id="View2" width="100%" height="100%" color="#3FCFE9">
</mx:Canvas>
</mx:ViewStack>
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FileDownLoadTest {
private static final int TCOUNT = 10;
private CountDownLatch latch = new CountDownLatch(TCOUNT);
private long completeLength = 0;
private long fileLength;
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
new FileDownLoadTest().download("http://localhost:8080/test/IESSAction.docx");
}
public void download(String address) throws Exception{
ExecutorService service = Executors.newFixedThreadPool(TCOUNT);
URL url = new URL(address);
URLConnection cn = url.openConnection();
cn.setRequestProperty("Referer", "http://www.test.com");
fileLength = cn.getContentLength();
long packageLength = fileLength/TCOUNT;
long leftLength = fileLength%TCOUNT;
RandomAccessFile file = new RandomAccessFile("d:\\test.docx","rw");
//計算每個線程請求文件的開始和結束位置
long pos = 0;
long endPos = pos + packageLength;
for(int i=0; i<TCOUNT; i++){
if(leftLength >0){
endPos ++;
leftLength--;
}
service.execute(new DownLoadThread(url, file, pos, endPos));
pos = endPos;
endPos = pos + packageLength;
}
System.out.println("waiting........................................");
long begin = System.currentTimeMillis();
latch.await();
file.close();
System.out.println("end........................................");
System.out.println(System.currentTimeMillis() - begin + "ms");
service.shutdown();
}
class DownLoadThread implements Runnable{
private URL url;
private RandomAccessFile file;
private long from;
private long end;
DownLoadThread(URL url, RandomAccessFile file, long from, long end){
this.url = url;
this.file = file;
this.from = from;
this.end = end;
}
public void run() {
long pos = from;
byte[] buf = new byte[512];
try {
HttpURLConnection cn = (HttpURLConnection) url.openConnection();
cn.setRequestProperty("Range", "bytes=" + from + "-" + end);
if(cn.getResponseCode() != 200 && cn.getResponseCode()!=206){
run();
return;
}
BufferedInputStream bis = new BufferedInputStream(cn.getInputStream());
int len ;
while((len = bis.read(buf)) != -1){
// synchronized(file){
file.seek(pos);
file.write(buf, 0, len);
// }
pos += len;
completeLength +=len;
System.out.println("threadName: " + Thread.currentThread().getName()
+ "persent: " + completeLength * 100 /fileLength + "%");
}
cn.disconnect();
latch.countDown();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
JAVA直接操作excel
/**
* @Author:何云龍
* @Version: 2012-11-16 下午03:45:16
* @Description:
*/
import jxl.*;
import java.io.*;
import jxl.write.*;
/**
* <p>
* java讀取Excel表格,復制、更新Excel工作薄
* </p>
*/
public class Test {
public static void main(String[] args) {
jxl.Workbook rwb = null;
try {
// 構建Workbook對象 只讀Workbook對象
// 直接從本地文件創建Workbook
// 從輸入流創建Workbook
InputStream is = new FileInputStream("D://Book1.xls");
rwb = Workbook.getWorkbook(is);
// Sheet(術語:工作表)就是Excel表格左下角的Sheet1,Sheet2,Sheet3但在程序中
// Sheet的下標是從0開始的
// 獲取第一張Sheet表
Sheet rs = rwb.getSheet(0);
// 獲取Sheet表中所包含的總列數
int rsColumns = rs.getColumns();
// 獲取Sheet表中所包含的總行數
int rsRows = rs.getRows();
// 獲取指這下單元格的對象引用
for (int i = 0; i < rsRows; i++) {
for (int j = 0; j < rsColumns; j++) {
Cell cell = rs.getCell(j, i);
System.out.print(cell.getContents() + " ");
}
System.out.println();
}
// 利用已經創建的Excel工作薄創建新的可寫入的Excel工作薄
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(new File(
"D://Book2.xls"), rwb);
// 讀取第一張工作表
jxl.write.WritableSheet ws = wwb.getSheet(0);
// 獲取第一個單元格對象
jxl.write.WritableCell wc = ws.getWritableCell(0, 0);
// 決斷單元格的類型,做出相應的轉化
if (wc.getType() == CellType.LABEL) {
Label l = (Label) wc;
l.setString("The value has been modified.");
}
// 寫入Excel對象
wwb.write();
wwb.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 操作完成時,關閉對象,翻譯占用的內存空間
rwb.close();
}
}
}
方法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();
}