java bufferedimage是什么,让我们一起了解一下?
BufferedImage是Image的一个子类,Image和BufferedImage的主要作用就是将一副图片加载到内存中。生成的图片在内存里有一个图像缓冲区,利用这个缓冲区我们可以很方便的操作这个图片,通常用来做图片修改操作如大小变换、图片变灰、设置图片透明或不透明等。
如果Java想将一副图片加载到内存中的方法是:BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filePath));
那么如果想编写一个网络程序,通过Socket将图片从服务器端传到客户端,并存入文件系统,该如何操作?
示例如下:
Server端: package org.exam3; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.net.ServerSocket; import java.net.Socket; import javax.imageio.ImageIO; public class T6Server { public static void main(String[] args) throws Exception { ServerSocket server = new ServerSocket(8888); Socket s = server.accept(); DataOutputStream dout = new DataOutputStream(s.getOutputStream()); BufferedImage image = ImageIO.read(new File("1.gif")); ByteArrayOutputStream out = new ByteArrayOutputStream(); boolean flag = ImageIO.write(image, "gif", out); byte[] b = out.toByteArray(); dout.write(b); s.close(); } } Client端: package org.exam3; import java.awt.BorderLayout; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.File; import java.io.PrintWriter; import java.net.Socket; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class T6Client extends JFrame { JButton button; MyPanel panel; public T6Client() { setSize(300, 400); button = new JButton("获取图像"); add(button,BorderLayout.NORTH); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { try { Socket s = new Socket("localhost",8888); PrintWriter out = new PrintWriter(s.getOutputStream()); out.print("a"); DataInputStream in = new DataInputStream(s.getInputStream()); byte[]b = new byte[1000000]; in.read(b); ByteArrayInputStream bin = new ByteArrayInputStream(b); BufferedImage image = ImageIO.read(bin); ImageIO.write(image, "gif", new File("2.gif")); s.close(); } catch (Exception e) { } } }); panel = new MyPanel(); add(panel); } public static void main(String[] args) throws Exception { T6Client frame = new T6Client(); frame.setDefaultCloseOperation(J
以上就是小编今天的分享了,希望可以帮助到大家。