Skip to content

Instantly share code, notes, and snippets.

@toybeans
Created October 20, 2015 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toybeans/225796f54369c13f70d6 to your computer and use it in GitHub Desktop.
Save toybeans/225796f54369c13f70d6 to your computer and use it in GitHub Desktop.
画像とテキストをTwitterとか共有出来るアプリに受け渡す
private void shareBitmap(Context context, String message) {
//ImageViewからbitmapを取得する
Bitmap b = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
Utility.writeBitmapExtarnalStorage(mContext,b);
// ファイル保存先 (SDカード)
String fileFullPath = Utility.getShareImageFilePath();
// ファイルを示すインテントを作成する
Uri uri = Uri.fromFile(new File(fileFullPath));
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpg"); // PNGの場合は "image/png" にする
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.putExtra(Intent.EXTRA_TEXT, message);
// 外部アプリを起動する
try {
context.startActivity(Intent.createChooser(intent, null));// 常に送信先を選択させる
} catch (ActivityNotFoundException e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
}
public static String getShareImageFilePath() {
String fname = "sample.jpg";
// ファイル保存先 (SDカード)
String fileFullPath = Environment.getExternalStorageDirectory()
+ File.separator + fname;
return fileFullPath;
}
/**
* SDカードにbitmapを保存する
*/
public static void writeBitmapExtarnalStorage(Context context, Bitmap b) {
// ファイル保存先 (SD)
String fileFullPath = Utility.getShareImageFilePath();
File file = new File(fileFullPath);
file.getParentFile().mkdir();
FileOutputStream out = null;
try {
// 画像をバイト配列に変換
ByteArrayOutputStream os = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, os); // PNGの場合は CompressFormat.PNG
os.flush();
byte[] w = os.toByteArray();
os.close();
// バイト配列をファイルとしてSDカードに書き出す
out = new FileOutputStream(fileFullPath);
out.write(w, 0, w.length);
out.flush();
} catch (FileNotFoundException ex) {
Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
} catch (IOException ex) {
Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ex) {
Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment