Android에서 이미지를 공유하기 위해 “Share image using”공유 의도를 사용하는 방법은 무엇입니까? 앱이 있습니다.

그 앱에 이미지 갤러리 앱이 있습니다. 모든 이미지를 drawable-hdpi 폴더에 넣었습니다. 내 활동에서 이미지를 다음과 같이 호출했습니다.

private Integer[] imageIDs = {
        R.drawable.wall1, R.drawable.wall2,
        R.drawable.wall3, R.drawable.wall4,
        R.drawable.wall5, R.drawable.wall6,
        R.drawable.wall7, R.drawable.wall8,
        R.drawable.wall9, R.drawable.wall10
};

이제 공유 의도를 사용 하여이 이미지를 공유하는 방법을 알고 싶습니다. 다음과 같은 공유 코드를 넣었습니다.

     Button shareButton = (Button) findViewById(R.id.share_button);
     shareButton.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {

        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        Uri screenshotUri = Uri.parse(Images.Media.EXTERNAL_CONTENT_URI + "/" + imageIDs);

        sharingIntent.setType("image/jpeg");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(sharingIntent, "Share image using"));

         }
    });

그리고 공유 버튼을 클릭 할 때도 공유 버튼이 있습니다. 공유 상자가 열립니다.하지만 대부분의 서비스가 충돌하거나 일부 서비스를 클릭하면 다음과 같이 말합니다. 이미지를 열 수 없습니다. 어떻게이 문제를 해결할 수 있거나 이미지를 공유 할 수있는 다른 형식 코드가 있습니까? ????

편집하다 :

아래 코드를 사용해 보았습니다. 그러나 작동하지 않습니다.

Button shareButton = (Button) findViewById(R.id.share_button);
     shareButton.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {

        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        Uri screenshotUri = Uri.parse("android.resource://com.android.test/*");
        try {
            InputStream stream = getContentResolver().openInputStream(screenshotUri);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        sharingIntent.setType("image/jpeg");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(sharingIntent, "Share image using"));

         }
    });

누군가가 위의 코드를 수정하거나 적절한 예제를 제공해도 괜찮다면 drawable-hdpi 폴더에서 내 이미지를 어떻게 공유합니까?



답변

Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
    f.createNewFile();
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
} catch (IOException e) {
        e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));


답변

superM에서 제안한 솔루션은 오랫동안 저에게 효과적 이었지만 최근에는 4.2 (HTC One)에서 테스트 한 후 작동을 멈췄습니다. 이것이 해결 방법이라는 것을 알고 있지만 모든 장치 및 버전에서 나를 위해 일한 유일한 방법이었습니다.

문서에 따르면 개발자는 “MediaStore 시스템 사용”을 요청받습니다. 바이너리 콘텐츠를 보내기 위해 . 그러나 이것은 미디어 콘텐츠가 장치에 영구적으로 저장된다는 (단점) 단점이 있습니다.

이것이 귀하를위한 옵션 인 경우 권한을 부여 WRITE_EXTERNAL_STORAGE하고 시스템 전체의 MediaStore를 사용할 수 있습니다.

Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");

ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
        values);


OutputStream outstream;
try {
    outstream = getContentResolver().openOutputStream(uri);
    icon.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
    outstream.close();
} catch (Exception e) {
    System.err.println(e.toString());
}

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


답변

먼저 권한 추가

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

리소스에서 비트 맵 사용

Bitmap b =BitmapFactory.decodeResource(getResources(),R.drawable.userimage);
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"));

블루투스 및 기타 메신저를 통해 테스트


답변

이 작업을 수행하는 가장 쉬운 방법은 MediaStore를 사용하여 공유하려는 이미지를 임시로 저장하는 것입니다.

Drawable mDrawable = mImageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap();

String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));

From : 인 텐트로 콘텐츠 공유


답변

Android에서 이미지를 progamatically 공유하는 방법 때로는 뷰의 스냅 샷을 찍고 공유하고 싶으므로 다음 단계를 따르십시오. 1. mainfest 파일에 권한 추가

<uses-permission
   android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2. 매우 먼저보기의 스크린 샷을 찍습니다. 예를 들어 Imageview, Textview, Framelayout, LinearLayout 등입니다.

예를 들어 oncreate ()에서이 메서드를 호출하여 스크린 샷을 찍을 이미지보기가 있습니다.

 ImageView image= (ImageView)findViewById(R.id.iv_answer_circle);
     ///take a creenshot
    screenShot(image);

스크린 샷을 찍은 후 버튼
클릭 또는 원하는 곳 에서 이미지 공유 방법

shareBitmap(screenShot(image),"myimage");

생성 후이 두 가지 방법을 정의 ##

    public Bitmap screenShot(View view) {
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
            view.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}

//////// this method share your image
private void shareBitmap (Bitmap bitmap,String fileName) {
    try {
        File file = new File(getContext().getCacheDir(), fileName + ".png");
        FileOutputStream fOut = new FileOutputStream(file);
        bitmap.compress(CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
        file.setReadable(true, false);
        final Intent intent = new Intent(     android.content.Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        intent.setType("image/png");
        startActivity(intent);
    } catch (Exception e) {
        e.printStackTrace();
    }

}


답변

갤러리에서 이미지를 공유하는 데 사용할 수있는 간단하고 쉬운 코드입니다.

 String image_path;
            File file = new File(image_path);
            Uri uri = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent .setType("image/*");
            intent .putExtra(Intent.EXTRA_STREAM, uri);
            context.startActivity(intent );


답변

다음은 나를 위해 일한 솔루션입니다. 한 가지 문제는 공유 또는 비 앱 비공개 위치 ( http://developer.android.com/guide/topics/data/data-storage.html#InternalCache )에 이미지를 저장해야한다는 것입니다.

많은 제안이 Apps“비공개”캐시 위치 에 저장하라고 말하고 있지만 이것은 물론 사용되는 일반 공유 파일 의도를 포함하여 다른 외부 응용 프로그램을 통해 액세스 할 수 없습니다. 이를 시도하면 실행되지만 예를 들어 dropbox는 파일을 더 이상 사용할 수 없다고 알려줍니다.

/ * STEP 1-아래 파일 저장 기능을 사용하여 비트 맵 파일을 로컬에 저장합니다. * /

localAbsoluteFilePath = saveImageLocally(bitmapImage);

/ * 2 단계-공유 파일 의도에 대한 비공개 절대 파일 경로 공유 * /

if (localAbsoluteFilePath!=null && localAbsoluteFilePath!="") {

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    Uri phototUri = Uri.parse(localAbsoluteFilePath);

    File file = new File(phototUri.getPath());

    Log.d(TAG, "file path: " +file.getPath());

    if(file.exists()) {
        // file create success

    } else {
        // file create fail
    }
    shareIntent.setData(phototUri);
    shareIntent.setType("image/png");
    shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
    activity.startActivityForResult(Intent.createChooser(shareIntent, "Share Via"), Navigator.REQUEST_SHARE_ACTION);
}

/ * 이미지 저장 기능 * /

    private String saveImageLocally(Bitmap _bitmap) {

        File outputDir = Utils.getAlbumStorageDir(Environment.DIRECTORY_DOWNLOADS);
        File outputFile = null;
        try {
            outputFile = File.createTempFile("tmp", ".png", outputDir);
        } catch (IOException e1) {
            // handle exception
        }

        try {
            FileOutputStream out = new FileOutputStream(outputFile);
            _bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();

        } catch (Exception e) {
            // handle exception
        }

        return outputFile.getAbsolutePath();
    }

/ * 3 단계-공유 파일 의도 결과 처리. 원격 임시 파일 등이 필요합니다. * /

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

            // deal with this with whatever constant you use. i have a navigator object to handle my navigation so it also holds all mys constants for intents
        if (requestCode== Navigator.REQUEST_SHARE_ACTION) {
            // delete temp file
            File file = new File (localAbsoluteFilePath);
            file.delete();

            Toaster toast = new Toaster(activity);
            toast.popBurntToast("Successfully shared");
        }


    }

누군가에게 도움이되기를 바랍니다.