I think I just found the solution. The general idea was the same with what I had said in the question.
About 2 hours earlier, I curiously transferred the very same image to a byte array in C# as well as Java. When I looked into the byte data I found that the [0,127] part of byte data was not "damaged". However, if an element in the C# array is greater than 127, e.g. C# byte: 137, 10001001, the corresponding element in the Java array would be its two's complement, e.g. Java byte: -119, 01110111. I think this is because the encoding and decoding way is different between C# and Java, I'm not quite sure. But all this is just about bit operation, so why do I care about this? All I need to do is to send the byte array from one side to another.
Here is the main methods:
C#:
public static byte[] ImageToBytes(string path)
{
FileInfo fileInfo = new FileInfo(path);
byte[] buffer = new byte[fileInfo.Length];
using (FileStream stream = fileInfo.OpenRead())
{
stream.Read(buffer, 0, buffer.Length);
}
return buffer;
}
public static bool sendBytes(byte[] content)
{
try
{
int length = content.Length;
sendCode(length);
clientSocket.Send(content);
return true;
}
catch
{
return false;
}
}
Java:
public static void byte2image(byte[] data, String path) {
if (data.length < 3 || path.equals(""))
return;
try {
FileImageOutputStream imageOutput = new FileImageOutputStream(
new File(path));
imageOutput.write(data, 0, data.length);
imageOutput.close();
System.out.println("Make Picture success,Please find image in "
+ path);
} catch (Exception ex) {
System.out.println("Exception: " + ex);
ex.printStackTrace();
}
}
public static byte[] readBytes(){
DataInputStream din=null;
int length=readCode();
byte[] b=new byte[length];
try {
din = new DataInputStream(socket.getInputStream());
din.read(b);
din.close();
} catch (IOException e) {
e.printStackTrace();
}
return b;
}