SoFunction
Updated on 2025-04-14

How to implement png to jpg picture on Android

1. Project Overview

Image processing is a very common requirement in Android application development. PNG and JPG are the two most common image formats:

  • PNG(Portable Network Graphics) supports transparent channels and lossless compression, suitable for scenarios where image quality and transparency are required;

  • JPG(Joint Photographic Experts Group) adopts lossy compression, does not support transparency, and has a smaller file size, which is suitable for photo display and network transmission.

The goals of this project are:

Implement a PNG to JPG module on the Android platform. Users can select PNG pictures from albums or files, convert them into JPG with one click and save them locally.

Core functional points:

  • Select PNG file from the system album or file manager

  • Read and decode as Bitmap

  • Handle transparent channels (fill background)

  • Compress and write files in JPG format

  • Return to the save path and preview it in the interface

2. Technical background and related knowledge

To complete the above functions, you need to master the following technical points:

1. Basic picture format

  • PNG

    • Supports RGBA quad-channel, where A (Alpha) channel is used for transparency

    • Lossless compression, large files

    • Suitable for icons, UI elements, scenes that require transparency

  • JPG

    • Only support RGB three channels, not transparent

    • Lossy compression, adjustable compression mass (0–100)

    • Small file size, suitable for photos and display pictures

2. Android Bitmap principle

  • BitmapIt is the core class for Android to process images, encapsulating pixel data.

  • Configuration Options

    • ARGB_8888: 32-bit, transparent, high quality

    • RGB_565: 16-bit, without transparency, less memory usage

  • Memory management

    • Large images can easily lead to OOM and need to be properly scaled or usedinSampleSize

    • You need to call after use()Free native memory

3. Canvas and Paint

  • Canvas: Draw a graph or other Bitmap on a Bitmap

  • Paint: Control drawing effects, such as anti-aliasing, color filters, etc.

Drawing process:

  1. Create a target Bitmap

  2. Bind this Bitmap with Canvas

  3. Draw by () method

4. Android file storage

  • Internal storage: Private, no permission required

  • External storage private directorygetExternalFilesDir()): No additional permissions are required, and will be cleared when uninstalling

  • External Public Directory / MediaStore: Requires runtime permission or use SAF

This project uses an external private directory to avoid cumbersome permissions.

5. Uri and ContentResolver

  • The system selector returns not the file path, butUri

  • Need to pass().openInputStream(uri)GetInputStream

6. Java I/O and exception handling

  • usetry–catch–finallyStructure ensures flow closure

  • CaptureIOException

7. Dynamic Permissions (API 23+)

  • If you use public external storage, you need to apply.WRITE_EXTERNAL_STORAGE

  • In this case, private directory is used without dynamic permissions

Ideas for project implementation

  1. UI Interaction

    • The main interface provides the "Select PNG" and "Start Conversion" buttons and ImageView

  2. Select a picture

    • useIntent.ACTION_PICKorIntent.ACTION_OPEN_DOCUMENTLimited type isimage/png

  3. Loading Bitmap

    • passContentResolverOpen Uri'sInputStream

    • use()Decode

  4. Create a target Bitmap

    • Call(width, height, Config.ARGB_8888)

  5. Handle transparent channels

    • First draw a pure white background on Canvas, then draw the original PNG

  6. Compress and save

    • use(, quality, outputStream)

    • Save togetExternalFilesDir("converted")

  7. Resource Recycling

    • Call()And close the stream

  8. Results Feedback

    • Return to the file path, the UI layer displays a preview and prompts the user

4. Complete code (integrated and detailed comments)

package ;
 
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
import ;
import ;
import ;
import ;
 
public class MainActivity extends Activity {
    private static final int REQUEST_PICK_PNG = 1001;
    private ImageView imageView;
    private Button btnSelect, btnConvert;
    private Uri selectedUri;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        (savedInstanceState);
        setContentView(.activity_main);
 
        // Bind UI controls        imageView = findViewById();
        btnSelect = findViewById();
        btnConvert = findViewById();
 
        // Select the PNG button and click        (new () {
            @Override
            public void onClick(View view) {
                // Start the system album, only PNG is displayed                Intent intent = new Intent(Intent.ACTION_PICK);
                ("image/png");
                startActivityForResult(intent, REQUEST_PICK_PNG);
            }
        });
 
        // Click on the conversion button        (new () {
            @Override
            public void onClick(View view) {
                // Make sure the picture is selected                if (selectedUri == null) {
                    (, "Please select PNG picture first", Toast.LENGTH_SHORT).show();
                    return;
                }
                // Call the tool class to perform the conversion                String jpgPath = (, selectedUri);
                if (jpgPath != null) {
                    // Conversion is successful: prompt and preview                    (, "Conversion successfully: " + jpgPath, Toast.LENGTH_LONG).show();
                    ((new File(jpgPath)));
                } else {
                    // Conversion failed: prompt                    (, "Conversion failed", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
 
    // Process the selection results    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        (requestCode, resultCode, data);
        if (requestCode == REQUEST_PICK_PNG && resultCode == RESULT_OK) {
            selectedUri = ();
            (selectedUri);
        }
    }
}
 
// Tool class: Execute PNG to JPGclass ImageConverter {
    private static final String TAG = "ImageConverter";
 
    /**
      * Convert PNG image to JPG and save
      *
      * @param context Application context
      * @param pngUri PNG image Uri
      * @return Returns the absolute path of the JPG file, and returns null if failed
      */
    public static String convertPngToJpg(Context context, Uri pngUri) {
        Bitmap srcBitmap = null;
        Bitmap dstBitmap = null;
        FileOutputStream fos = null;
 
        try {
            // 1. Open the PNG input stream            InputStream is = ().openInputStream(pngUri);
            // 2. Decode to Bitmap            srcBitmap = (is);
            if (srcBitmap == null) {
                (TAG, "Decoding PNG Bitmap failed");
                return null;
            }
 
            // 3. Create a target Bitmap, use ARGB_8888 to retain high quality            dstBitmap = (
                    (),
                    (),
                    .ARGB_8888
            );
 
            // 4. Draw with Canvas: white background + original image            Canvas canvas = new Canvas(dstBitmap);
            (); // Fill in white background            Paint paint = new Paint();
            (true);     // Anti-aliasing            (srcBitmap, 0, 0, paint);
 
            // 5. Prepare the output file            File outDir = ("converted");
            if (outDir != null && !()) {
                ();
            }
            File jpgFile = new File(outDir, "img_" + () + ".jpg");
            fos = new FileOutputStream(jpgFile);
 
            // 6. Compressed to JPG, 90% quality            boolean ok = (, 90, fos);
            ();
            if (ok) {
                (TAG, "JPG saved successfully: " + ());
                return ();
            } else {
                (TAG, "Return false");
                return null;
            }
 
        } catch (IOException e) {
            (TAG, "Conversion exception: " + ());
            return null;
 
        } finally {
            // 7. Resource release            if (srcBitmap != null) ();
            if (dstBitmap != null) ();
            if (fos != null) {
                try { (); } catch (IOException ignored) {}
            }
        }
    }
}

5. Code interpretation

  • onActivityResult(...)
    Processes the PNG file Uri returned by the system and displays it in ImageView for user confirmation.

  • convertPngToJpg(...)

    • Open the PNG input stream and decode it as the source Bitmap;

    • Create the target Bitmap (ARGB_8888);

    • Use Canvas to draw a white background, and then draw the source Bitmap to eliminate the black background problem in transparent areas;

    • Prepare the output file path (App private external storage), and create a directory;

    • Callcompress(JPEG, 90, fos)Write the target Bitmap to the file in JPG format;

    • Release Bitmap and close the stream.

6. Project Summary and Expansion

  1. Review of core technology points

    • Bitmap decoding and creation

    • Canvas drawing and transparent processing

    • Compression and file writing

    • Uri → InputStream → Bitmap process

    • Use of external private directories to avoid complicating permissions

  2. Performance and stability

    • useARGB_8888Ensure quality, if necessary, change it toRGB_565To save memory;

    • For large images, you can first zoom as needed to avoid OOM;

    • Make sure to release resources in finally to prevent memory leaks.

  3. Extensible features

    • Batch conversion: Iterate through multiple images and use thread pool to process concurrently;

    • Dynamic compression quality: Add SeekBar to the UI, and the user can adjust the quality value;

    • Other formats support: Extended to PNG→WEBP, BMP→JPG, etc.;

    • Save to system album: Add JPG to albums through the MediaStore API;

    • Transparent background customization: Allows users to choose background color instead of fixed white;

    • Error Feedback: Enhance exception capture and show users the detailed reason for the error;

    • Progress display: Display progress bar or notification during batch conversion.

  4. Key points for learning

    • A deep understanding of Android image processing flow;

    • Master file storage best practices;

    • Familiar with common Bitmap configuration and memory optimization techniques;

    • Master the use of Canvas to perform secondary processing of bitmaps.

The above is the detailed content of Android's method to convert png to jpg pictures. For more information about Android's png to jpg pictures, please follow my other related articles!