gpt4 book ai didi

android - 如何从图库中选择图像并将其设置为位图

转载 作者:行者123 更新时间:2023-11-30 01:23:50 26 4
gpt4 key购买 nike

我在 RecyclerView.Adapter 中有 imageButton,它需要创建一个 intent 从图片库中选择图片。这是我在 onImageSelected(uri, getContentResolver())

方法中将 Uri 传递给适配器的主类
public class MainForSemesterMessageFeedT extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK) {
if(data != null) {
Uri uri = data.getData();
FeedListAdapter adapter = new FeedListAdapter();
adapter.onImageSelected(uri, getContentResolver());
}
}
}

这是适配器类:

public class FeedListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_FEED = 1;

private int PICK_IMAGE_REQUEST = 1;
private Bitmap bitmap;
private ImageView img;
private Uri filepath;


private List<FeedItem> feedItems;
Context context;
Activity activity;
private SQLiteHandler db;
private StringRequest stringRequest;
private RequestQueue requestQueue;

private ImageLoader imageLoader = AppController.getInstance().getImageLoader();


public FeedListAdapter() {

}

public FeedListAdapter(List<FeedItem> feedItems, Activity activity) {
this.feedItems = feedItems;
this.activity = activity;
notifyItemRangeChanged(0, feedItems.size());
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
this.context = parent.getContext();
if (viewType == TYPE_HEADER) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_header, parent, false);
return new VHHeader(v);
} else if (viewType == TYPE_FEED) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_item_row, parent, false);
return new VHItem(v);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof VHItem) {
FeedItem feedItem = getItem(position);
((VHItem) holder).name.setText(feedItem.getName());
//converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(Long.parseLong(feedItem.getTimeStamp()), System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
((VHItem) holder).timestamp.setText(timeAgo);
if (!TextUtils.isEmpty(feedItem.getStatus())) {
((VHItem) holder).statusMsg.setText(feedItem.getStatus());
((VHItem) holder).statusMsg.setVisibility(View.VISIBLE);
} else {
((VHItem) holder).statusMsg.setVisibility(View.GONE);
}

if (feedItem.getUrl() != null) {
((VHItem) holder).url.setText(Html.fromHtml("<a href=\"" + feedItem.getUrl() + "\">" + feedItem.getUrl() + "</a> "));
// making url clickable
((VHItem) holder).url.setMovementMethod(LinkMovementMethod.getInstance());
((VHItem) holder).url.setVisibility(View.VISIBLE);
} else {
((VHItem) holder).url.setVisibility(View.GONE);
}
((VHItem) holder).profilePic.setImageUrl(feedItem.getProfilePic(), imageLoader);

if (feedItem.getImge() != null) {
((VHItem) holder).feedImageView.setImageUrl(feedItem.getImge(), imageLoader);
((VHItem) holder).feedImageView.setVisibility(View.VISIBLE);
((VHItem) holder).feedImageView.setResponseObserver(new FeedImageView.ResponseObserver() {
@Override
public void onError() {

}

@Override
public void onSuccess() {

}
});
} else {
((VHItem) holder).feedImageView.setVisibility(View.GONE);
}
} else if (holder instanceof VHHeader) {
db = new SQLiteHandler(context);
HashMap<String, String> data = db.getUserDetails();
((VHHeader) holder).imageView.setImageUrl(data.get("photo"), imageLoader);
String user_question = ((VHHeader) holder).editText.getText().toString().trim();

// here I set the image from bitmap to imageview
((VHHeader) holder).headerImageView.setImageBitmap(bitmap);
((VHHeader) holder).headerImageView.setVisibility(View.VISIBLE);

Message.message(context, ""+bitmap);
}


}

private FeedItem getItem(int position) {
return feedItems.get(position - 1);
}

@Override
public int getItemCount() {
return feedItems.size() + 1;
}

@Override
public long getItemId(int position) {
return super.getItemId(position);
}

// We need to work here in VHHeader. the other ViewHolder "VHItem" is to parse data from json so no need to worry about it
private class VHHeader extends RecyclerView.ViewHolder implements View.OnClickListener {
EditText editText;
ImageView headerImageView;
NetworkImageView imageView;
Button post;
ImageButton selectImageBtn;


public VHHeader(View v) {
super(v);
//this one I need to show the pic. which Visibility is visible in onBindViewHolder
headerImageView = (ImageView) v.findViewById(R.id.header_imageview);
editText = (EditText) v.findViewById(R.id.header_tv);
selectImageBtn = (ImageButton) v.findViewById(R.id.header_select_img);
imageView = (NetworkImageView) v.findViewById(R.id.header_user_photo);
post = (Button) v.findViewById(R.id.header_post_btn);
post.setOnClickListener(this);
selectImageBtn.setOnClickListener(this);

}

@Override
public void onClick(View view) {
HashMap<String, String> data = db.getUserDetails();
final String user_id = data.get("uid");
final String display_picture = data.get("photo");
final String name = data.get("name");
final String user_post = editText.getText().toString().trim();

// also dont worry about this post. its just to post the status. it works fine.
if (view.getId() == post.getId()) {
stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_ADD_FEED, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("RESPONSE", response.toString());
try {
JSONObject object = new JSONObject(response);
boolean error = object.getBoolean("error");
if (!error) {
Message.message(context, "Posted");
notifyDataSetChanged();

} else {
String error_msg = object.getString("error_msg");
Message.message(context, error_msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Message.message(context, error.getMessage());
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
long millis = System.currentTimeMillis() % 1000;
Map<String, String> param = new HashMap<String, String>();
param.put("user_id", user_id);
param.put("name", name);
param.put("status", user_post);
param.put("q_image", "");
param.put("display_picture", display_picture);
param.put("timestamp", String.valueOf(millis));
return param;
}
};
requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);

}
// Here I choose the image from gallary. works fine.
if(view.getId() == selectImageBtn.getId()) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
activity.startActivityForResult(intent, PICK_IMAGE_REQUEST);
}

}
}


// Dont wory about this. it is use to parse data from json.
private class VHItem extends RecyclerView.ViewHolder {
TextView name, timestamp, statusMsg, url;
NetworkImageView profilePic;
FeedImageView feedImageView;

public VHItem(View v) {
super(v);
if (imageLoader == null) {
AppController.getInstance().getImageLoader();
}
name = (TextView) itemView.findViewById(R.id.name);
timestamp = (TextView) itemView.findViewById(R.id.timestamp);
statusMsg = (TextView) itemView.findViewById(R.id.txtStatusMsg);
url = (TextView) itemView.findViewById(R.id.txtUrl);
profilePic = (NetworkImageView) itemView.findViewById(R.id.profilePic);
feedImageView = (FeedImageView) itemView.findViewById(R.id.feedImage1);

}
}


@Override
public int getItemViewType(int position) {
if (isPositionHeader(position)) {
return TYPE_HEADER;
} else {
return TYPE_FEED;
}
}

private boolean isPositionHeader(int position) {
return position == 0;
}


// This is used to encode image. I didnot used this method anywhere yet. will use it for server storing.
public String getStringImage(Bitmap btmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
btmp.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}

// The uri comes from Acitivity
public void onImageSelected(Uri uri, ContentResolver contentResolver) {
try {
bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri);
// when i show this bitmap in Toast. I throws null pointer exception here too.
} catch (IOException e) {
e.printStackTrace();
}
}

我很困惑如何从 Adapter 中的图库中选择图像并将其存储在位图中,以便我可以使用该位图图像执行其他任务,例如将其发送到在线数据库。

This is the screenshot of the app

最佳答案

//add this to your manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

//add to your activity
private static int IMAGE_GALLERY_REQUEST =1;
//add to your onclick method
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data=Uri.parse(pictureDirectoryPath);
photoPickerIntent.setDataAndType(data,"image/*");
startActivityForResult(photoPickerIntent,IMAGE_GALLERY_REQUEST);
//add to your activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_GALLERY_REQUEST) {
Uri imageUri = data.getData();
InputStream inputstream;
try {
inputstream = getContentResolver().openInputStream(imageUri);
//the "image" received here it the image itself
Bitmap image = BitmapFactory.decodeStream(inputstream);
//YOU CAN ASSIGN IT TO YOUR IMAGE BUTTON HERE IF YOU WANT
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

关于android - 如何从图库中选择图像并将其设置为位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36723371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com