27

I have a cropped bitmap image and I need to save it into a jpeg file.

Thanks in advance

Mohammad Elsayed
  • 1,625
  • 1
  • 14
  • 38
Carlo Matulessy
  • 925
  • 1
  • 12
  • 26

3 Answers3

37

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

DragonFire
  • 2,836
  • 1
  • 23
  • 40
Piyush
  • 24,288
  • 6
  • 40
  • 72
6

Try this

bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outStream);

Here is a sample Program

compressing-a-bitmap-to-jpg-format-android

Karthi
  • 746
  • 4
  • 16
2

I think this is what you need

bitmap.compress(CompressFormat.JPEG, 90, outputStream);

I hope this will help you.

Pooja Sangle
  • 321
  • 2
  • 10
  • 1
    Good point. To those who don't know how to use this approach: 1. `ByteArrayOutputStream out = new ByteArrayOutputStream();` 2. `bitmap.compress(CompressFormat.JPEG, 90, out);` 3. write byte[] into file or use it anywhere else (for example you can show it in ImageView with the help of Glide lib) – Kirill Karmazin Oct 31 '18 at 21:27