본문 바로가기

안드로이드

이미지 공유시 Uri 얻기

 

   Bitmap bitmap = decodeFile(file);
   Uri uri = shareFile(bitmap);

   share(uri);



public  Uri shareFile(Bitmap bitmap) {
    Date now = new Date();
    String fileName = "android_share_" + now + ".jpg";
    Uri imageUri=null;

    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
    try {
        int quality = 100;

        OutputStream fos;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentResolver resolver = getActivity().getContentResolver();
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
            contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
            imageUri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
            fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
        } else {
            String imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
            File image = new File(imagesDir, fileName);
            fos = new FileOutputStream(image);

            imageUri = Uri.fromFile(image);
        }

        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
        fos.flush();
        fos.close();



    } catch (IOException e) {
        e.printStackTrace();
    }

    return imageUri;

}


private void share(Uri uri) {
    try {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");

        // Set the image file URI
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);

        // Optional: Add a subject and text to the sharing content
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "이미지 공유");

        // Grant permission for receiving apps to read the content URI
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        // Start the intent
        startActivity(Intent.createChooser(shareIntent, "이미지 공유"));
    }catch (Exception e){
        Log.d("myLog", " share  error  " + e.toString());
    }


}