Java 如何从数据库中检索保存的图像?
我已经创建了一个配置文件。现在,我可以保存个人资料图片,但我不知道如何检索图像。我试过了,但没有得到任何解决方案 当我再次访问配置文件时,上传图像后,我现在做了一些更改,图像视图变得不可见。请检查我的代码,我哪里出错了? 我已经尝试从共享首选项获取图像,但仍然无法正常工作 这是我的密码:Java 如何从数据库中检索保存的图像?,java,android,Java,Android,我已经创建了一个配置文件。现在,我可以保存个人资料图片,但我不知道如何检索图像。我试过了,但没有得到任何解决方案 当我再次访问配置文件时,上传图像后,我现在做了一些更改,图像视图变得不可见。请检查我的代码,我哪里出错了? 我已经尝试从共享首选项获取图像,但仍然无法正常工作 这是我的密码: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my__profile);
edt_btn = findViewById(R.id.edt_btn);
user_pname = findViewById(R.id.user_profile_name);
ButterKnife.bind(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//
loadProfileDefault();
ImagePicker.clearCache(this);
sharedPreferenceClass = new SharedPreferenceClass(this);
sharedPreferenceClass = new SharedPreferenceClass(My_Profile.this);
user_id = sharedPreferenceClass.getValue_string("user_id");
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
edt_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(My_Profile.this,Editprofile.class);
startActivity(intent);
}
});
sharedPreferences=getApplicationContext().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
final String name=sharedPreferenceClass.getName();
user_pname.setText(name);
String profileImage = sharedPreferences.getString("profile_image", "");
bitmap = decodeToBase64(profileImage);
imgProfile.setImageBitmap(bitmap);
}
private void loadProfile(String url) {
Log.d(TAG, "Image cache path: " + url);
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(url));
imgProfile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
Glide.with(this).load(url)
.into(imgProfile);
imgProfile.setColorFilter(ContextCompat.getColor(this, android.R.color.transparent));
upload();
}
private void upload() {
sharedPreferences = getApplicationContext().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
final byte[][] imageBytes = {baos.toByteArray()};
final String imgProfile1 = Base64.encodeToString(imageBytes[0], Base64.DEFAULT);
Log.d("converted to string",imgProfile1);
StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://www.khaokamao.in/ndokan/api/profile_pic.php", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String status = jsonObject.getString("status");
String message = jsonObject.getString("msg");
Log.i("Message",message);
Toast.makeText(getApplicationContext(), status + message + " ", Toast.LENGTH_LONG).show();
if (status.equalsIgnoreCase("Success")) {
Log.i("response",response);
JSONObject jsonObject1 = jsonObject.getJSONObject("data");
imageBytes[0] = Base64.decode(imgProfile1, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes[0], 0, imageBytes[0].length);
imgProfile.setImageBitmap(decodedImage);
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(My_Profile.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("profile_image",imgProfile1);
editor.commit();
Log.d("put_img","put_image");
editor.apply();
} else {
Toast.makeText(My_Profile.this, "Please Try Again..", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id",user_id);
params.put(KEY_PROFILE,imgProfile1);
return params;
}
};
stringRequest.setShouldCache(false);
int socketTimeout = 60000; // 30 seconds. You can change it
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
RequestQueue requestQueue = Volley.newRequestQueue(My_Profile.this);
requestQueue.add(stringRequest);
}
private void loadProfileDefault() {
Glide.with(this).load(bitmap)
.into(imgProfile);
imgProfile.setColorFilter(ContextCompat.getColor(this, R.color.profile_default_tint));
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String profileImage = sharedPreferences.getString("profile_image", "");
bitmap = decodeToBase64(profileImage);
imgProfile.setImageBitmap(bitmap);
}
@OnClick({R.id.img_profile})
void onProfileImageClick() {
Dexter.withActivity(this)
.withPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) {
showImagePickerOptions();
}
if (report.isAnyPermissionPermanentlyDenied()) {
showSettingsDialog();
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
private void showImagePickerOptions() {
ImagePicker.showImagePickerOptions(this, new ImagePicker.PickerOptionListener() {
@Override
public void onTakeCameraSelected() {
launchCameraIntent();
}
@Override
public void onChooseGallerySelected() {
launchGalleryIntent();
}
});
}
private void launchCameraIntent() {
Intent intent = new Intent(My_Profile.this, ImagePicker.class);
intent.putExtra(ImagePicker.INTENT_IMAGE_PICKER_OPTION, ImagePicker.REQUEST_IMAGE_CAPTURE);
// setting aspect ratio
intent.putExtra(ImagePicker.INTENT_LOCK_ASPECT_RATIO, true);
intent.putExtra(ImagePicker.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
intent.putExtra(ImagePicker.INTENT_ASPECT_RATIO_Y, 1);
// setting maximum bitmap width and height
intent.putExtra(ImagePicker.INTENT_SET_BITMAP_MAX_WIDTH_HEIGHT, true);
intent.putExtra(ImagePicker.INTENT_BITMAP_MAX_WIDTH, 1000);
intent.putExtra(ImagePicker.INTENT_BITMAP_MAX_HEIGHT, 1000);
startActivityForResult(intent, REQUEST_IMAGE);
}
private void launchGalleryIntent() {
Intent intent = new Intent(My_Profile.this, ImagePicker.class);
intent.putExtra(ImagePicker.INTENT_IMAGE_PICKER_OPTION, ImagePicker.REQUEST_GALLERY_IMAGE);
// setting aspect ratio
intent.putExtra(ImagePicker.INTENT_LOCK_ASPECT_RATIO, true);
intent.putExtra(ImagePicker.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
intent.putExtra(ImagePicker.INTENT_ASPECT_RATIO_Y, 1);
startActivityForResult(intent, REQUEST_IMAGE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == REQUEST_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getParcelableExtra("path");
// You can update this bitmap to your server
// loading profile image from local cache
loadProfile(uri.toString());
}
}
}
private void showSettingsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(My_Profile.this);
builder.setTitle(getString(R.string.dialog_permission_title));
builder.setMessage(getString(R.string.dialog_permission_message));
builder.setPositiveButton(getString(R.string.go_to_settings), (dialog, which) -> {
dialog.cancel();
openSettings();
});
builder.setNegativeButton(getString(android.R.string.cancel), (dialog, which) -> dialog.cancel());
builder.show();
}
// navigating user to app settings
private void openSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}
here is my xml code
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/img_profile"
android:layout_width="150dp"
android:layout_height="150dp"
android:src="@drawable/useree1"
app:civ_border_width="2dp"
app:civ_border_color="#FF000000"
android:elevation="10dp"
android:scaleType="centerCrop"
android:layout_below="@+id/header_cover_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="-80dp"/>
<de.hdodenhof.circleimageview.CircleImageView
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u my\u profile);
edt_btn=findViewById(R.id.edt_btn);
user\u pname=findviewbyd(R.id.user\u profile\u name);
把(这个)绑起来;
Toolbar Toolbar=findviewbyd(R.id.Toolbar);
设置支持操作栏(工具栏);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//
loadProfileDefault();
ImagePicker.clearCache(这个);
sharedPreferenceClass=新的sharedPreferenceClass(此);
sharedPreferenceClass=新的sharedPreferenceClass(My_Profile.this);
user_id=SharedReferenceClass.getValue_字符串(“user_id”);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
edt_btn.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
Intent Intent=新的Intent(My_Profile.this,Editprofile.class);
星触觉(意向);
}
});
SharedReferences=getApplicationContext().GetSharedReferences(“userinfo”,Context.MODE\u PRIVATE);
最终字符串名称=sharedPreferenceClass.getName();
user_pname.setText(名称);
String profileImage=sharedPreferences.getString(“profile_image”,”);
位图=解码为SE64(profileImage);
imgProfile.setImageBitmap(位图);
}
私有void加载配置文件(字符串url){
Log.d(标记,“图像缓存路径:”+url);
试一试{
位图=MediaStore.Images.Media.getBitmap(this.getContentResolver(),Uri.parse(url));
imgProfile.setImageBitmap(位图);
}捕获(IOE异常){
e、 printStackTrace();
}
Glide.with(this.load)(url)
.into(imgProfile);
setColorFilter(ContextCompat.getColor(this,android.R.color.transparent));
上传();
}
私有无效上载(){
SharedReferences=getApplicationContext().GetSharedReferences(“userinfo”,Context.MODE\u PRIVATE);
ByteArrayOutputStream bas=新的ByteArrayOutputStream();
压缩(bitmap.CompressFormat.JPEG,50,baos);
最终字节[][]图像字节={baos.toByteArray()};
最终字符串imgProfile1=Base64.encodeToString(imageBytes[0],Base64.DEFAULT);
Log.d(“转换为字符串”,imgProfile1);
StringRequest StringRequest=新的StringRequest(Request.Method.POST)https://www.khaokamao.in/ndokan/api/profile_pic.php,新的响应。侦听器(){
@凌驾
公共void onResponse(字符串响应){
试一试{
JSONObject JSONObject=新JSONObject(响应);
String status=jsonObject.getString(“status”);
String message=jsonObject.getString(“msg”);
Log.i(“消息”,消息);
Toast.makeText(getApplicationContext(),状态+消息+“”,Toast.LENGTH_LONG).show();
if(status.equalsIgnoreCase(“Success”)){
Log.i(“响应”,响应);
JSONObject JSONObject 1=JSONObject.getJSONObject(“数据”);
imageBytes[0]=Base64.decode(imgProfile1,Base64.DEFAULT);
位图decodedImage=BitmapFactory.decodeByteArray(imageBytes[0],0,imageBytes[0]。长度);
imgProfile.setImageBitmap(解码图像);
SharedReferences SharedReferences=PreferenceManager.GetDefaultSharedReferences(My_Profile.this);
SharedReferences.Editor=SharedReferences.edit();
编辑器.putString(“profile_image”,imgProfile1);
commit();
Log.d(“放置图像”、“放置图像”);
editor.apply();
}否则{
Toast.makeText(My_Profile.this,“请重试…”),Toast.LENGTH_SHORT.show();
}
}捕获(JSONException e1){
e1.printStackTrace();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_SHORT).show();
}
}) {
@凌驾
受保护的映射getParams()引发AuthFailureError{
Map params=新的HashMap();
参数put(“用户id”,用户id);
参数put(键配置文件,imgProfile1);
返回参数;
}
};
stringRequest.setShouldCache(false);
int-socketTimeout=60000;//30秒。您可以更改它
RetryPolicy policy=新的DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT\u最大重试次数,
DefaultRetryPolicy.DEFAULT\u BACKOFF\u MULT);
stringRequest.setRetryPolicy(策略);
RequestQueue RequestQueue=Volley.newRequestQueue(My_Profile.this);
添加(stringRequest);
}
私有void loadProfileDefault(){
滑动。使用(此)。加载(位图)
.into(imgProfile);
imgProfile.setColorFilter(ContextCompat.getColor(this,R.color.profile_default_tint));
共享数据引用
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String profileImage = sharedPreferences.getString("profile_image", "");
Bitmap bitmap = decodeToBase64(profileImage);
public static Bitmap decodeToBase64(String str) {
byte[] decodedByte = Base64.decode(str, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
ImageView imgView = findViewById(R.id.imageview);
Glide
.with(context)
.load(imageBytes)
.centerCrop()
.into(imgView);