如何使用按钮分享图像?

How to share image with a button?

我正在制作二维码生成器 到目前为止,我制作了一个生成器按钮和保存按钮。 它工作正常。 我正在尝试使用共享按钮。 作为初学者需要几天的时间才能弄清楚,但我仍然无法让它发挥作用。 在这段代码中,如果我点击分享,应用就会关闭。

/**Barcode share*/

        findViewById(R.id.share_barcode).setOnClickListener(v -> {
            Bitmap b = BitmapFactory.decodeResource(getResources(),R.id.qr_image);
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/jpeg");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
            Uri imageUri =  Uri.parse(path);
            share.putExtra(Intent.EXTRA_STREAM, imageUri);
            startActivity(Intent.createChooser(share, "Select"));
        });

我猜是路径问题。 我使用 savepath 来保存二维码图像。然后可能与 String path 冲突 所以我尝试了 String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";; 它不工作。所以也许这是不同的问题,我不知道如何解决。 你能告诉我如何解决吗?

MainActivity

public class MainActivity extends AppCompatActivity {

    private String inputValue;
    private String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
    private Bitmap bitmap;
    private QRGEncoder qrgEncoder;
    private ImageView qrImage;
    private EditText edtValue;
    private AppCompatActivity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        qrImage = findViewById(R.id.qr_image);
        edtValue = findViewById(R.id.edt_value);
        activity = this;


/**Barcode Generator*/
        findViewById(R.id.generate_barcode).setOnClickListener(view -> {
            inputValue = edtValue.getText().toString().trim();
            if (inputValue.length() > 0) {
                WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
                Display display = manager.getDefaultDisplay();
                Point point = new Point();
                display.getSize(point);
                int width = point.x;
                int height = point.y;
                int smallerDimension = width < height ? width : height;
                smallerDimension = smallerDimension * 3 / 4;

                qrgEncoder = new QRGEncoder(
                        inputValue, null,
                        QRGContents.Type.TEXT,
                        smallerDimension);
                qrgEncoder.setColorBlack(Color.BLACK);
                qrgEncoder.setColorWhite(Color.WHITE);
                try {
                    bitmap = qrgEncoder.getBitmap();
                    qrImage.setImageBitmap(bitmap);
                } catch (Exception e) {
                    e.printStackTrace();

                }
            } else {
                edtValue.setError(getResources().getString(R.string.value_required));
            }
        });
/**Barcode save*/
        findViewById(R.id.save_barcode).setOnClickListener(v -> {
            String filename = edtValue.getText().toString().trim();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                try {
                    ContentResolver resolver = getContentResolver();
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename + ".jpg");
                    contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
                    contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
                    Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                    OutputStream fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    Objects.requireNonNull(fos).close();
                    Toast toast= Toast.makeText(getApplicationContext(),
                            "Image Saved. Check your gallery.", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
                    toast.show();

                    edtValue.setText(null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    try {
                        boolean save = new QRGSaver().save(savePath, filename, bitmap, QRGContents.ImageType.IMAGE_JPEG);
                        String result = save ? "Image Saved. Check your gallery." : "Image Not Saved";
                        Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
                        edtValue.setText(null);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                }
            }
        });


        /**Barcode share*/

        findViewById(R.id.share_barcode).setOnClickListener(v -> {
            Bitmap b = BitmapFactory.decodeResource(getResources(),R.id.qr_image);
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/jpeg");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
            Uri imageUri =  Uri.parse(path);
            share.putExtra(Intent.EXTRA_STREAM, imageUri);
            startActivity(Intent.createChooser(share, "Select"));
        });



    }


}

我认为你可以通过以下方式解决这个问题:

  1. 将位图保存在文件中。
  2. 然后在意图中共享该文件的 URI。

在下面的代码中,我将图片保存在app级目录,你可以选择自己的,代码是用kotlin写的。

注意:如果您使用应用级目录来保存图像,那么您必须使用提供的文件来获取 URI,否则可能会导致 FileUriExposedException

try {
    val file = File(getExternalFilesDir(null),System.currentTimeMillis().toString() + ".png")
    file.createNewFile()
    val b = imageView.drawable.toBitmap()
    FileOutputStream(file).use { out ->
        b.compress(Bitmap.CompressFormat.PNG, 100, out)
    }

    val share = Intent(Intent.ACTION_SEND)
    share.type = "image/jpeg"
    val photoURI = FileProvider.getUriForFile(this, applicationContext.packageName.toString() + ".provider", file)

    share.putExtra(Intent.EXTRA_STREAM, photoURI)
    startActivity(Intent.createChooser(share, "Share Image"))

    Toast.makeText(this, "Completed!!", Toast.LENGTH_SHORT).show()
} catch (e: IOException) {
    e.printStackTrace()
    Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
}

在JAVA中:


public void shareImage(Activity activity, ImageView imageView) {
        try {
            File file = new File(activity.getExternalFilesDir(null), System.currentTimeMillis() + ".png");
            file.createNewFile();

            Bitmap bitmap = drawableToBitmap(imageView.getDrawable());
            FileOutputStream fOut = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
            fOut.flush();
            fOut.close();
    
            Intent share = new Intent("android.intent.action.SEND");
            share.setType("image/jpeg");
            Uri photoURI = FileProvider.getUriForFile(activity,activity.getPackageName(), file);
            share.putExtra("android.intent.extra.STREAM", photoURI);
            activity.startActivity(Intent.createChooser(share, "Share Image"));
        } catch (Exception var14) {

        }
    }

    public static Bitmap drawableToBitmap (Drawable drawable) {
        Bitmap bitmap;

        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            if(bitmapDrawable.getBitmap() != null) {
                return bitmapDrawable.getBitmap();
            }
        }

        if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
            bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
        } else {
            bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    }