2008年10月19日 星期日

[Java] 串流圖片下載範例

串流圖片下載範例:

Solution1:

URL url = new URL("http://xxx/xxx/image.jpg");
FileOutputStream fos = new FileOutputStream("image.jpg", false);
InputStream is = url.openStream();
int r = 0;
while((r = is.read()) != -1)
fos.write(r);
fos .close();


Solution2:

private static void flash(InputStream in, OutputStream out, int chunkSize){
try {

byte[] b = new byte[chunkSize];
int readLen;

while ((readLen = in.read(b, 0, b.length)) != -1) {
out.write(b, 0, readLen);
}

out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}


Solution3:


import java.io.FileOutputStream;
import java.awt.Image;
import java.awt.image.BufferedImage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;


public class JpgTest {

public JpgTest() {

try {
JpgTset();
} catch (Exception ex) {

}
}

public void JpgTset()
throws Exception {
URL url = null;
url = new URL("http://www.jsinfo.net/advimage/3721/765_70_cartoon1.jpg");
//File _file = new File("/Order005-0001.jpg"); //讀入文件
//Image src = Toolkit.getDefaultToolkit().getImage("http://www.google.com/images/logo_sm.gif");
// Image src = java.awt.Toolkit.getDefaultToolkit().getDefaultToolkit().createImage("http://www.google.com/images/logo_sm.gif");
Image src = javax.imageio.ImageIO.read(url); //構造Image對象
int wideth = src.getWidth(null); //得到源圖寬
int height = src.getHeight(null); //得到源圖長
BufferedImage tag = new BufferedImage(wideth / 2, height / 2,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src, 0, 0, wideth / 2, height / 2, null); //繪製縮小後的圖
FileOutputStream out = new FileOutputStream("c:/765_70_cartoon.jpg"); //輸出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); //近JPEG編碼
//System.out.print(width+"*"+height);
out.close();
}

public static void main(String[] args) {
JpgTest untitled11 = new JpgTest();
}
}


[REF]http://www.javaworld.com.tw/jute/post/view?bid=5&id=237541&tpg=1&ppg=1&sty=0&age=0#237541
[REF]http://topic.csdn.net/t/20060310/01/4604719.html

沒有留言:

張貼留言