我试图从我的应用程序中打开画廊内置应用程序中的图像/图片。
我有一个图片的URI(图片位于SD卡上)。
你有什么建议吗?
我试图从我的应用程序中打开画廊内置应用程序中的图像/图片。
我有一个图片的URI(图片位于SD卡上)。
你有什么建议吗?
当前回答
package com.ImageConvertingDemo;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
public class MyActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText tv = (EditText)findViewById(R.id.EditText01);
ImageView iv = (ImageView)findViewById(R.id.ImageView01);
FileInputStream in;
BufferedInputStream buf;
try
{
in = new FileInputStream("/sdcard/smooth.png");
buf = new BufferedInputStream(in,1070);
System.out.println("1.................."+buf);
byte[] bMapArray= new byte[buf.available()];
tv.setText(bMapArray.toString());
buf.read(bMapArray);
Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
/*for (int i = 0; i < bMapArray.length; i++)
{
System.out.print("bytearray"+bMapArray[i]);
}*/
iv.setImageBitmap(bMap);
//tv.setText(bMapArray.toString());
//tv.setText(buf.toString());
if (in != null)
{
in.close();
}
if (buf != null)
{
buf.close();
}
}
catch (Exception e)
{
Log.e("Error reading file", e.toString());
}
}
}
其他回答
这里有两个关于图像拾取器的有用教程,可下载源代码:
如何创建Android图像拾取器
如何在Android上选择和裁剪图像
但是,应用程序有时会被迫关闭,你可以通过添加android:configChanges属性到Manifest文件中的主活动来修复它:
<activity android:name=".MainActivity"
android:label="@string/app_name" android:configChanges="keyboardHidden|orientation" >
似乎相机API失去了对方向的控制,所以这将有助于它。:)
检索特定类型的文件
这个示例将获得图像的副本。
static final int REQUEST_IMAGE_GET = 1;
public void selectImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_IMAGE_GET);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_GET && resultCode == RESULT_OK) {
Bitmap thumbnail = data.getParcelable("data");
Uri fullPhotoUri = data.getData();
// Do work with photo saved at fullPhotoUri
...
}
}
打开特定类型的文件
在4.4或更高版本上运行时,您请求打开由另一个应用程序管理的文件
static final int REQUEST_IMAGE_OPEN = 1;
public void selectImage() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("image/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Only the system receives the ACTION_OPEN_DOCUMENT, so no need to test.
startActivityForResult(intent, REQUEST_IMAGE_OPEN);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_OPEN && resultCode == RESULT_OK) {
Uri fullPhotoUri = data.getData();
// Do work with full size photo saved at fullPhotoUri
...
}
}
原始来源
万一有用的话;我这样做是为了得到位图:
InputStream is = context.getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
以下解决方案适用于2.3(姜饼)-4.4(奇巧),5.0(棒棒糖)和6.0(棉花糖)也:-
步骤1打开图库选择图片的代码:
public static final int PICK_IMAGE = 1;
private void takePictureFromGalleryOrAnyOtherFolder()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
步骤2 onActivityResult中获取数据的代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_IMAGE) {
Uri selectedImageUri = data.getData();
String imagePath = getRealPathFromURI(selectedImageUri);
//Now you have imagePath do whatever you want to do now
}//end of inner if
}//end of outer if
}
public String getRealPathFromURI(Uri contentUri) {
//Uri contentUri = Uri.parse(contentURI);
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = null;
try {
if (Build.VERSION.SDK_INT > 19) {
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[] { id }, null);
} else {
cursor = context.getContentResolver().query(contentUri,
projection, null, null, null);
}
} catch (Exception e) {
e.printStackTrace();
}
String path = null;
try {
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
} catch (NullPointerException e) {
e.printStackTrace();
}
return path;
}
这是我的例子,可能不完全是你的情况。
假设你从你的API提供者获得base64格式,给它一个文件名和文件扩展名,将它保存到文件系统中的某个位置。
public static void shownInBuiltInGallery(final Context ctx, String strBase64Image, final String strFileName, final String strFileExtension){
new AsyncTask<String, String, File>() {
@Override
protected File doInBackground(String... strBase64Image) {
Bitmap bmpImage = convertBase64StringToBitmap(strBase64Image[0], Base64.NO_WRAP);
if(bmpImage == null) {
cancel(true);
return null;
}
byte[] byImage = null;
if(strFileExtension.compareToIgnoreCase(FILE_EXTENSION_JPG) == 0) {
byImage = convertToJpgByte(bmpImage); // convert bitmap to binary for latter use
} else if(strFileExtension.compareToIgnoreCase(FILE_EXTENSION_PNG) == 0){
byImage = convertToPngByte(bmpImage); // convert bitmap to binary for latter use
} else if(strFileExtension.compareToIgnoreCase(FILE_EXTENSION_BMP) == 0){
byImage = convertToBmpByte(bmpImage); // convert bitmap to binary for latter use
} else {
cancel(true);
return null;
}
if(byImage == null) {
cancel(true);
return null;
}
File imageFolder = ctx.getExternalCacheDir();
if(imageFolder.exists() == false){
if(imageFolder.mkdirs() == false){
cancel(true);
return null;
}
}
File imageFile = null;
try {
imageFile = File.createTempFile(strFileName, strFileExtension, imageFolder);
} catch (IOException e){
e.printStackTrace();
}
if(imageFile == null){
cancel(true);
return null;
}
if (imageFile.exists() == true) {
if(imageFile.delete() == false){
cancel(true);
return null;
}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile.getPath());
fos.write(byImage);
fos.flush();
fos.close();
} catch (java.io.IOException e) {
e.printStackTrace();
} finally {
fos = null;
}
return imageFile;
}
@Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
String strAuthority = ctx.getPackageName() + ".provider";
Uri uriImage = FileProvider.getUriForFile(ctx, strAuthority, file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uriImage, "image/*");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
ctx.startActivity(intent);
}
}.execute(strBase64Image);}
不要忘记在AndroidManifest.xml中首先设置一个适当的文件提供程序
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
文件路径是XML在…/res/ XML /file_path.xml
<?xml version="1.0" encoding="utf-8"?>
<external-files-path name="external_files" path="Accessory"/>
<external-path name="ex_Download" path="Download/" />
<external-path name="ex_Pictures" path="Pictures/" />
<external-files-path name="my_Download" path="Download/" />
<external-files-path name="my_Pictures" path="Pictures/" />
<external-cache-path name="my_cache" path="." />
<files-path name="private_Download" path="Download/" />
<files-path name="private_Pictures" path="Pictures/" />
<cache-path name="private_cache" path="." />
长话短说,首先准备好文件提供程序,将已知且可访问的图片源的Uri传递给Intent,否则,将图片保存在所需的位置,然后将位置(作为Uri)传递给Intent。