How to convert a bitmap to a jpeg file in Android?

Carlo Matulessy picture Carlo Matulessy · Dec 2, 2013 · Viewed 44.8k times · Source

I'm a little bit lost here. I have to convert a bitmap from a cropped image to an .jpeg file. I have looked to other related questions but none of them were relative to mine. (most were reverted as file to bitmap)

Thanks in advance

ps. first time Android development

Answer

Piyush picture Piyush · Dec 2, 2013

Use this:

Bitmap bmp = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();

for that you can use this:

FileInputStream fileInputStream = null;

File file = new File("yourfile");

byteArray = new byte[(int) file.length()];

try {
    //convert file into array of bytes
    fileInputStream = new FileInputStream(file);
    fileInputStream.read(bFile);
    fileInputStream.close();

    //convert array of bytes into file
    FileOutputStream fileOuputStream =
            new FileOutputStream("C:\\testing2.txt");
    fileOuputStream.write(bFile);
    fileOuputStream.close();

    System.out.println("Done");
} catch (Exception e) {
    e.printStackTrace();
}

and also for more info go with here