Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Copy Image to clipboard/clipdata

Long press on images in the web or at other places gives me the opportunity to copy an image to the clipboard of my device. See here:

Example

Now I want to implement this into my app. What I have so far:

Code

Bitmap bitmap = getBitmap();
        File file = storeImage(bitmap, name);

        //Share
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        Uri uri = Uri.fromFile(file);
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);

        //Add Copy to Clipboard to choosers
        Intent clipboard = new Intent(this, CopyToClipboardImageActivity.class);
        clipboard.setData(uri);

        Intent chooserIntent = Intent.createChooser(shareIntent, getString(R.string.shareScreenshot));
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{clipboard});
        startActivity(chooserIntent);

CopyToClipboardImageActivity

  public class CopyToClipboardImageActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            Uri uri = getIntent().getData();
            if (uri != null) {
                copyImageToClipboard(uri);
                Toast.makeText(this, getString(R.string.hinweisInZwischenablageKopiert), Toast.LENGTH_SHORT).show();
            }

            // Finish right away. We don't want to actually display a UI.
            finish();
        }

        private void copyImageToClipboard(Uri uri) {
            ClipboardManager mClipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ContentValues values = new ContentValues(2);
            values.put(MediaStore.Images.Media.MIME_TYPE, "Image/jpg");
            values.put(MediaStore.Images.Media.DATA,  "file://"+uri.getPath());

            ContentResolver theContent = getContentResolver();
            Uri imageUri = theContent.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            ClipData theClip = ClipData.newUri(getContentResolver(), "Image", imageUri);
            mClipboard.setPrimaryClip(theClip);
        }
    }

But this does not work yet. Either it only copies a weird path to the clipboard (See above picture^^) or I get the following NullpointerException:

Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference

in this line ClipData theClip = ClipData.newUri(getContentResolver(), "Image", imageUri);

like image 773
XxGoliathusxX Avatar asked Jul 19 '16 02:07

XxGoliathusxX


People also ask

How do you copy pictures to clipboard on Android?

Go to the Images folder and look for the image you want to copy. Long press the image. Tap on the copy icon at the bottom left. Your image is now copied to the clipboard.

How do I copy an image in Android 11?

If you happen to be on the latest version of Android — Android 11 — you'd be able to copy any image from anywhere you wish. You'd just need access the 'Recents' screen, long-press an image, and tap 'Copy. '


1 Answers

Don't use the MediaStore database values. Save the image to the sdcard where you have permission to use it. How to get permissions (mainifest):

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.html2pdf"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="16"
            android:targetSdkVersion="19" />
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"         />    
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"        />
                <activity
            android:name=".CopyToClipboardImageActivity"
            android:label="@string/app_name" >
                <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="image/*" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.SEND_MULTIPLE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="image/*" />
    </intent-filter>
        </activity>
some code:

        final File sdcard = Environment.getExternalStorageDirectory();
        String absoluteFilePath = sdcard.getAbsolutePath() + "/tmp.jpg";
        File aFile = saveBitmap(bitmap , sdcard.getAbsolutePath(), "tmp", Bitmap.CompressFormat.JPEG);


            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("image/*");
            Uri uri = Uri.fromFile(new File(absoluteFilePath));
            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
            startActivity(shareIntent );

    /**
     * Saves the bitmap by given directory, filename, and format; if the directory is given null,
     * then saves it under the cache directory.
     */
    int DEFAULT_COMPRESS_QUALITY = 100;
    public File saveBitmap(
            Bitmap bitmap, String directory, String filename, CompressFormat format) 
    {
        if (directory == null) 
        {
            directory = this.getCacheDir().getAbsolutePath();
        } else 
        {
            // Check if the given directory exists or try to create it.
            File file = new File(directory);
            if (!file.isDirectory() && !file.mkdirs()) 
            {
                return null;
            }
        }

        File file = null;
        OutputStream os = null;
        try {
            filename = (format == CompressFormat.PNG) ? filename + ".png" : filename + ".jpg";
            file = new File(directory, filename);
            os = new FileOutputStream(file);
            bitmap.compress(format, DEFAULT_COMPRESS_QUALITY, os);
        } catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return file;
    }
}

This clipboard stuff does not work for pasting images, see: Copy-Paste image in Android using Clipboard Manager

like image 163
Jon Goodwin Avatar answered Oct 10 '22 04:10

Jon Goodwin