问题描述:

I need to read an image file and send it to a web browser using HTTP protocol, and I cannot figure out how to send the bytes of the image. I cannot for the life of me figure it out. Thanks in advance. Here is my code:

import java.awt.image.BufferedImage;

import java.io.BufferedInputStream;

import java.io.BufferedReader;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.ArrayList;

import javax.imageio.ImageIO;

public class Main {

byte[] byt=null;

public String read(String message){

String httpHeader="";

String toReturn="";

try{

if(message!=null){

String[] parts=message.split("\n");

String[] RequstParts=parts[0].split(" ");

System.out.println("This is a "+RequstParts[0]+" request for "+RequstParts[1]);

if(RequstParts[1].equals("/"))RequstParts[1]="index.html";

if(RequstParts[0].equals("GET")){

if(RequstParts[1].endsWith(".html")){

httpHeader="HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";

BufferedReader in = new BufferedReader(new FileReader(new File("WebContent/"+RequstParts[1])));

String line="";

while(null!=(line=in.readLine())){

toReturn+=line;

}

}else if(RequstParts[1].endsWith(".jpg")){

httpHeader="HTTP/1.1 200 OK\r\nContent-Type: image/jpg\r\nContent-Length: 13312\r\n\r\n";

}

}

}

}catch(Exception e){

toReturn+="<br>ERROR: "+e.toString();

return httpHeader+toReturn;

}

return httpHeader+toReturn;

}

public Main(){

try{

ServerSocket listener = new ServerSocket(9090);

System.out.println("HTTP server started!");

while(true){

Socket socket = listener.accept();

System.out.println("\nRecieved Data!");

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

String message=read(in.readLine());

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

System.out.println("\nSENDING "+message);

out.println(message);

out.println(byt);

out.close();

}

}catch(Exception e){

System.out.println("ERROR "+e.toString());

e.printStackTrace();

}

}

public static void main(String args[]){

new Main();

}

}

网友答案:

This should work:

public byte[] extractBytes (String ImageName) throws IOException {
 // open image
 File imgPath = new File(ImageName);
 BufferedImage bufferedImage = ImageIO.read(imgPath);

 // get DataBufferBytes from Raster
 WritableRaster raster = bufferedImage .getRaster();
 DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

 return ( data.getData() );
}

So call this extractBytes on an image (specified as a filename to the method here), and send the returned byte[] using:

OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(byte[]);

Method code taken from here.

相关阅读:
Top