ImageIO.write()를 이용하여 이미지 파일을 생성하는 예
ImageIO.write() 는 다음과 같 3가지 형태로 사용할 수 있다.
static boolean write(RenderedImage im, String formatName, File output)
static boolean write(RenderedImage im, String formatName, ImageOutputStream output)
static boolean write(RenderedImage im, String formatName, OutputStream output)
다음은 위에 제시된 방법 중 첫번째, File 클래스를 이용하여 이미지 파일을 생성하는 예이다
3번째 방법을 이용하면 Socket 등으로 연결된 원격 시스템에 이미지 데이터를 전달할 수도 있다.
// URL 클래스를 이용하여 이미지 파일을 로드하여 BufferedImage로 전환하는 예 URL imgURL = getClass().getResource("images/smile.jpg"); try { img = ImageIO.read(imgURL); // 로컬 시스템에 이미지 파일을 생성하는 예 ImageIO.write(img, "jpg", new File("D:/test/myFile.jpg")); System.out.println("이미지 파일 생성 성공"); } catch (Exception e) { e.printStackTrace(); }
소켓을 통해 이미지를 수신하는 예 BufferedImage image = ImageIO.read(socket.getInputStream()); ImageIcon icon = new ImageIcon(image); jLabel.setIcon(icon); 소켓을 통해 이미지를 전송하는 예 BufferedImage image = ....; ImageIO.write(image, "PNG", socket.getOutputStream());
혹은 아래처럼 일반 바이트 스트림을 사용하여 이미지를 전송할 수도 있다
import java.io.*; import java.net.*; public class client{ public static void main(String args[]){ try { Socket s = new Socket("x.x.x.x", 9500); BufferedOutputStream imagebos = new BufferedOutputStream(s.getOutputStream()); int c =0, i=0; File inputFile = new File("something.jpg"); FileInputStream infile = new FileInputStream(inputFile); File outputFile = new File("outagain.jpg"); FileOutputStream outfile = new FileOutputStream(outputFile); System.out.println("Client"); byte[] buf = new byte[4096]; int read = 0; while((read = infile.read(buf,0,buf.length))!=-1){ imagebos.write(buf,0,read); outfile.write(buf,0,read); } System.out.println(i+" Stuff"); infile.close(); imagebos.flush(); imagebos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }