Android 将图像复制到剪贴板/clipdata

标签 android image copy jpeg clipboard

长按网络或其他地方的图片让我有机会将图片复制到我设备的剪贴板。看这里:

Example

现在我想将它实现到我的应用程序中。到目前为止我所拥有的:

代码

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);
        }
    }

但这还行不通。要么它只复制一个奇怪的路径到剪贴板(见上图^^)要么我得到以下 NullpointerException:

尝试在空对象引用上调用虚方法“java.lang.String android.net.Uri.getScheme()”

在这一行 ClipData theClip = ClipData.newUri(getContentResolver(), "Image", imageUri);

最佳答案

不要使用 MediaStore 数据库值。将图像保存到您有权使用它的 sdcard 中。如何获取权限(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;
    }
}

此剪贴板内容不适用于粘贴图像,请参阅: Copy-Paste image in Android using Clipboard Manager

关于Android 将图像复制到剪贴板/clipdata,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38448677/

相关文章:

sql - 将 .txt 文件加载到 Postgres 数据库中

java - 如何在没有 byteBuffer.array() 的情况下将一个 byteBuffer 部分复制到另一个 byteBuffer

javascript - 使用 javascript 为用户提供图像下载

c++ - 如何为这种 C++ 结构实现复制运算符?

Android HelloOpenGLES20 示例不起作用

java - Android - 任务 ':app:compileDebugJava' 执行失败,预期为 ';'

html - 响应定位图像

c# - 在打开文件对话框之前显示图片框中的默认图片

android - 为什么我不能更改工具栏文本大小?

java - 无法使用 Apache 从 Android 向 Django Web 服务器发出 http 请求