Liya
Liya

Reputation: 628

How to download an image in socket connection and remove the unwanted bytes

I need to download an image throught socket connection. Currently I have a byte array which contains a .jpg file also some other unwanted bytes (ffd8). I need to remove these unwanted bytes from my byte array. I tried to download the file without removing the bytes then I got image in corrupted format. So I would like to know how can I remove the unwanted bytes from my bytearray.

Here in my code:

  while (!status) {
                        byte[] buffer = new byte[1024]; // or 4096, or more
                        int bytesRead = input.read(buffer, 0, buffer.length);
                        int availableBytes = input.available();

                        str2 = str2.append(bytesRead);
                        ImageDataArray = concat(ImageDataArray, buffer);
                        countPackets = countPackets + buffer.length;
                        if (input.available() != 0) {
                            System.out.println("String:" + str1.toString());
                        } else break;
                    }
                    System.out.println("--------------------out of while ------------------");
                    File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "/SteelmanPro/1020/images/image" +filename1);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                }
                write(ImageDataArray, Environment.getExternalStorageDirectory().getAbsoluteFile() + "/SteelmanPro/1020/images/image" +filename1);

concat() method:

 public  byte[] concat(byte[]...arrays)
{
    // Determine the length of the result array
    int totalLength = 0;
    for (int i = 0; i < arrays.length; i++)
    {
        totalLength += arrays[i].length;
    }

    // create the result array
    byte[] result = new byte[totalLength];

    // copy the source arrays into the result array
    int currentIndex = 0;
    for (int i = 0; i < arrays.length; i++)
    {
        System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length);
        currentIndex += arrays[i].length;
    }

    return result;
}

write method:

 void write(byte[] aInput, String aOutputFileName) {

    Log.e("dfd", "Writing binary file...");
    try {
        OutputStream output = null;
        try {
            output = new BufferedOutputStream(new FileOutputStream(aOutputFileName));
            output.write(aInput);
        } finally {
            if (output != null)
                output.close();
        }
    } catch (FileNotFoundException ex) {
        Log.e("dfd", "File not found.");
    } catch (IOException ex) {
        Log.e("dfd", "" + ex);
    }
}

Upvotes: 0

Views: 135

Answers (2)

user207421
user207421

Reputation: 310860

Your code is littered with errors.

while (!status) {
    byte[] buffer = new byte[1024]; // or 4096, or more

This array should be allocated outside the loop.

    int bytesRead = input.read(buffer, 0, buffer.length);
    int availableBytes = input.available();

Calling available() is usually pointless, and this is no exception, not least because you aren't using availableBytes anywhere.

     str2 = str2.append(bytesRead);

If this is an image you should not be storing it in a String. String is not a container for binary data.

        ImageDataArray = concat(ImageDataArray, buffer);

As you haven't posted ImageDataArray it is impossible to know what this means.

        countPackets = countPackets + buffer.length;

Wrong. It should be countPackets + bytesRead. You cannot assume that read() fills the buffer. That's why it returns a value.

        if (input.available() != 0) {

Another misuse of available(). It is not a test for end of stream, or end of message.

            System.out.println("String:" + str1.toString());
        } else break;
    }
    System.out.println("--------------------out of while ------------------");
    File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "/SteelmanPro/1020/images/image" +filename1);
     if (!file.exists()) {
         file.createNewFile();
    }

As you are about to create a new FileOutputStream(...) with the same name, this block is not only redundant but wasteful.

}
write(ImageDataArray, Environment.getExternalStorageDirectory().getAbsoluteFile() + "/SteelmanPro/1020/images/image" +filename1);

As you haven't posted this write() method it is impossible to comment on it.

concat() method:

public  byte[] concat(byte[]...arrays)

The signature is already wrong. You don't know that any of these arrays is filled. See above.

{
    // Determine the length of the result array
    int totalLength = 0;
    for (int i = 0; i < arrays.length; i++)
    {
        totalLength += arrays[i].length;
    }

    // create the result array
    byte[] result = new byte[totalLength];

    // copy the source arrays into the result array
    int currentIndex = 0;
    for (int i = 0; i < arrays.length; i++)
    {
        System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length);
        currentIndex += arrays[i].length;
    }
    return result;
}

You don't need the entire method. You should write data to the file as you received it. Instead of wasting memory and adding latency.

Don't write code like this.

Upvotes: 1

Marcin Orlowski
Marcin Orlowski

Reputation: 75619

Which contains a .jpg file also some other unwanted bytes (ffd8) I tried to download the file without removing the bytes then I got image in corrupted format

As removing FFD8 made you end up with corrupted and you still try to do that, what needs to happen to make you stop thinking that "unwanted" bytes are actually "very wanted"? (pun intended)

In fact FF D8 FF is JPEG's magic number and is part of the JPEG file.

https://en.wikipedia.org/wiki/JPEG

Upvotes: 1

Related Questions