我试图从我的应用程序中打开画廊内置应用程序中的图像/图片。
我有一个图片的URI(图片位于SD卡上)。
你有什么建议吗?
我试图从我的应用程序中打开画廊内置应用程序中的图像/图片。
我有一个图片的URI(图片位于SD卡上)。
你有什么建议吗?
当前回答
最快的方式打开图像从画廊或相机。
原始参考:从画廊在android程序中获取图像
下面的方法将从图库或相机接收图像,并将其显示在ImageView中。所选图像将存储在内部。
XML代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.exampledemo.parsaniahardik.uploadgalleryimage.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Capture Image and upload to server" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Below image is fetched from server"
android:layout_marginTop="5dp"
android:textSize="23sp"
android:gravity="center"
android:textColor="#000"/>
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:scaleType="fitXY"
android:src="@mipmap/ic_launcher"
android:id="@+id/iv"/>
</LinearLayout>
JAVA类
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.androidquery.AQuery;
import org.json.JSONException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity implements AsyncTaskCompleteListener{
private ParseContent parseContent;
private Button btn;
private ImageView imageview;
private static final String IMAGE_DIRECTORY = "/demonuts_upload_camera";
private final int CAMERA = 1;
private AQuery aQuery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parseContent = new ParseContent(this);
aQuery = new AQuery(this);
btn = (Button) findViewById(R.id.btn);
imageview = (ImageView) findViewById(R.id.iv);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
String path = saveImage(thumbnail);
try {
uploadImageToServer(path);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void uploadImageToServer(final String path) throws IOException, JSONException {
if (!AndyUtils.isNetworkAvailable(MainActivity.this)) {
Toast.makeText(MainActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show();
return;
}
HashMap<String, String> map = new HashMap<String, String>();
map.put("url", "https://demonuts.com/Demonuts/JsonTest/Tennis/uploadfile.php");
map.put("filename", path);
new MultiPartRequester(this, map, CAMERA, this);
AndyUtils.showSimpleProgressDialog(this);
}
@Override
public void onTaskCompleted(String response, int serviceCode) {
AndyUtils.removeSimpleProgressDialog();
Log.d("res", response.toString());
switch (serviceCode) {
case CAMERA:
if (parseContent.isSuccess(response)) {
String url = parseContent.getURL(response);
aQuery.id(imageview).image(url);
}
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
}
其他回答
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());
}
}
}
在上面代码的基础上,我反映了如下代码,可能它更适合:
public String getPath(Uri uri) {
String selectedImagePath;
//1:MEDIA GALLERY --- query from MediaStore.Images.Media.DATA
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if(cursor != null){
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
selectedImagePath = cursor.getString(column_index);
}else{
selectedImagePath = null;
}
if(selectedImagePath == null){
//2:OI FILE Manager --- call method: uri.getPath()
selectedImagePath = uri.getPath();
}
return selectedImagePath;
}
检索特定类型的文件
这个示例将获得图像的副本。
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
...
}
}
原始来源
这里有两个关于图像拾取器的有用教程,可下载源代码:
如何创建Android图像拾取器
如何在Android上选择和裁剪图像
但是,应用程序有时会被迫关闭,你可以通过添加android:configChanges属性到Manifest文件中的主活动来修复它:
<activity android:name=".MainActivity"
android:label="@string/app_name" android:configChanges="keyboardHidden|orientation" >
似乎相机API失去了对方向的控制,所以这将有助于它。:)
我通过@hcpl和@mad的解决方案。hcpl的解决方案很好地支持图库中的本地图像& mad在此基础上提供了一个更好的解决方案-它也有助于加载OI/Astro/Dropbox图像。但在我的应用程序中,虽然在picasa库工作,现在集成在Android画廊,这两个解决方案都失败了。
我进行了一些搜索和分析,最终得出了一个更好和优雅的解决方案,克服了这一限制。感谢Dimitar Darazhanski的博客,在这种情况下,他帮助了我,我修改了一些,使它更容易理解。这是我的解
public class BrowsePicture extends Activity {
//YOU CAN EDIT THIS TO WHATEVER YOU WANT
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
//ADDED
private String filemanagerstring;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
Log.d("URI VAL", "selectedImageUri = " + selectedImageUri.toString());
selectedImagePath = getPath(selectedImageUri);
if(selectedImagePath!=null){
// IF LOCAL IMAGE, NO MATTER IF ITS DIRECTLY FROM GALLERY (EXCEPT PICASSA ALBUM),
// OR OI/ASTRO FILE MANAGER. EVEN DROPBOX IS SUPPORTED BY THIS BECAUSE DROPBOX DOWNLOAD THE IMAGE
// IN THIS FORM - file:///storage/emulated/0/Android/data/com.dropbox.android/...
System.out.println("local image");
}
else{
System.out.println("picasa image!");
loadPicasaImageFromGallery(selectedImageUri);
}
}
}
}
// NEW METHOD FOR PICASA IMAGE LOAD
private void loadPicasaImageFromGallery(final Uri uri) {
String[] projection = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if(cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(MediaColumns.DISPLAY_NAME);
if (columnIndex != -1) {
new Thread(new Runnable() {
// NEW THREAD BECAUSE NETWORK REQUEST WILL BE MADE THAT WILL BE A LONG PROCESS & BLOCK UI
// IF CALLED IN UI THREAD
public void run() {
try {
Bitmap bitmap = android.provider.MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
// THIS IS THE BITMAP IMAGE WE ARE LOOKING FOR.
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
}
}
cursor.close();
}
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if(cursor != null) {
//HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
//THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
else
return uri.getPath(); // FOR OI/ASTRO/Dropbox etc
}
检查一下,如果有什么问题请告诉我。我已经测试过了,它在每种情况下都很好。
希望这对大家有所帮助。