如何保存新的imagebutton图片并在重新启动时加载新创建的imagebutton图片

应用程序关闭后,我试图在imagebutton中重新加载从图库或相机中获取的图像

我尝试将其保存到文件中并从该文件加载,但是我无法使其正常工作。




public class HomeFragment extends Fragment {


    ImageButton profilePic;

    Drawable myDrawable;
    Bitmap bitmap ;




    String photoPath = Environment.getExternalStorageDirectory().toString();

    public View onCreateView(@NonNull LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
               View root = inflater.inflate(R.layout.fragment_home,container,false);



       profilePic = (ImageButton) root.findViewById(R.id.imageButton);
        myDrawable = profilePic.getBackground();
        bitmap = drawableToBitmap(myDrawable);


// set up listener on ImageButton to load method changeProfilePicture() when user clicks profilePic
        profilePic.setOnClicklistener(new View.OnClicklistener() {
            public void onClick(View v) {

                changeProfilePicture();
            }
        });


        int Permission_All = 1;

        String[] Permissions = {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if(!hasPermissions(getactivity(),Permissions)){
            activityCompat.requestPermissions(getactivity(),Permissions,Permission_All);

        }


       loadImageFromStorage(photoPath);
        return root;

    }


    public void onResume() {

        super.onResume();

        loadImageFromStorage(photoPath);

    }

    public void onStart() {

        super.onStart();

    }

    public void onPause() {

        super.onPause();


    }

    public void onStop() {

        super.onStop();

        saveBitmap(bitmap);
    }

    public void onDestroy() {

        super.onDestroy();


    }

    static final int REQUEST_IMAGE_CAPTURE = 1;
    static final int REQUEST_GALLERY = 0;

    //create changeProfilePicture method and call it when the  ImageButton is pressed
    public void changeProfilePicture() {

// add alert dialog to ask user how they would like to change their profile icon



    }


    // override onactivityResult to allow the imageButton to be changed to picture taken from camera or gallery

    public void onactivityResult(int requestCode,int resultCode,Intent data) {
        super.onactivityResult(requestCode,resultCode,data);

        if(resultCode == RESULT_OK) {
            //create a switch based on requestCode
            switch (requestCode) {
                // if user clicks change profilePic through gallery use picture user picked from gallery
                case REQUEST_GALLERY:
                    Uri galleryImage = data.getData();
                    try {
                        Bitmap galleryBitmap = MediaStore.Images.Media.getBitmap(getactivity().getcontentResolver(),galleryImage);
                        galleryBitmap = Bitmap.createScaledBitmap(galleryBitmap,200,false);
                        profilePic.setImageBitmap(galleryBitmap);
                       saveBitmap(galleryBitmap);
                    } catch (IOException e) {
                        Log.i("TAG","Exception " + e);
                    }

                    break;
                // if user clicks change profilePic through camera use picture user took from camera app

                case REQUEST_IMAGE_CAPTURE:

                    Bundle extras = data.getExtras();
                    Bitmap imageBitmap = (Bitmap) extras.get("data");
                    imageBitmap = Bitmap.createScaledBitmap(imageBitmap,false);
                    profilePic.setImageBitmap(imageBitmap);
                    saveBitmap(imageBitmap);

                    break;
            }

        }
    }



    private void saveBitmap(Bitmap bm){
        File file = Environment.getExternalStorageDirectory();
        File newFile = new File(file,"myImage.jpg");

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(newFile);
            bm.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.i( "getExternalStorageDirectory",file.getPath()) ;
    }

    private void loadImageFromStorage(String path)
    {

        try {
            File f=new File(path,"myImage.jpg");
            Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
            profilePic.setImageBitmap(b);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }

    }

    public static Bitmap drawableToBitmap (Drawable drawable) {
        Bitmap bitmap = null;

        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            if(bitmapDrawable.getBitmap() != null) {
                return bitmapDrawable.getBitmap();
            }
        }

        if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
            bitmap = Bitmap.createBitmap(1,1,Bitmap.Config.ARGB_8888);
        } else {
            bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(),Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(bitmap);
        drawable.setbounds(0,canvas.getWidth(),canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    public static boolean hasPermissions(Context context,String... permissions)
    {

        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M && context!=null && permissions!=null){
            for(String permission: permissions){
                if(activityCompat.checkSelfPermission(context,permission)!= PackageManager.PERMISSION_GRANTED){
                    return  false;
                }
            }
        }
        return true;
    }

}



// what I have for my ImageButton in xml

   <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:contentDescription="@string/profilePic"
        android:onClick="changeProfilePicture"
        android:paddingLeft="0dp"
        android:paddingTop="0dp"
        android:paddingRight="0dp"
        android:paddingBottom="0dp"
        android:layout_marginTop="2dp"
        android:layout_marginBottom="5dp"
        android:background="#0000"
        app:srcCompat="@mipmap/ic_launcher_round" />

I have the following permissions inside the manifest.xml 

 <uses-feature
        android:name="android.hardware.camera"
        android:required="true" /> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我正在尝试从结果中保存新的ImageButton并在重新启动应用程序时加载它。可以使用ImageButton完成吗?可以将其保存到文件并从中加载吗?

exchange456 回答:如何保存新的imagebutton图片并在重新启动时加载新创建的imagebutton图片

第一步,您需要像这样从imageButton获取位图

Bitmap bitmap = ((BitmapDrawable)imageButton.getDrawable()).getBitmap();

接下来,您需要将此位图保存到这样的外部存储

private void saveBitmap(Bitmap bm){
    File file = Environment.getExternalStorageDirectory();
    File newFile = new File(file,"myImage.jpg");

    try {
        FileOutputStream fileOutputStream = new FileOutputStream(newFile);
        bm.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

然后像这样加载此保存的位图

private void loadImageFromStorage(String path)
{

    try {
        File f=new File(path,"myImage.jpg");
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
        imageButton.setImageBitmap(b);
    } 
    catch (FileNotFoundException e) 
   {
    e.printStackTrace();
   }

}

您应该这样定义图像路径

String photoPath = Environment.getExternalStorageDirectory() + "/myImage.jpg";

这是主要思想,您可以通过在没有可用图像保存时设置默认图像来在代码中添加一些风味。

希望这是寻找的东西。

更新:

您需要更改此行

Bitmap bitmap = ((BitmapDrawable)imageButton.getDrawable()).getBitmap();

对此

Drawable myDrawable = imageButton.getBackground();

之后,您将此Drawable转换为Bitmap

Bitmap bitmap = drawableToBitmap(myDrawable);

这是此转换的功能

public static Bitmap drawableToBitmap (Drawable drawable) {
    Bitmap bitmap = null;

    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        if(bitmapDrawable.getBitmap() != null) {
            return bitmapDrawable.getBitmap();
        }
    }

    if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
        bitmap = Bitmap.createBitmap(1,1,Bitmap.Config.ARGB_8888); 
    } else {
        bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(),Bitmap.Config.ARGB_8888);
    }

    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0,canvas.getWidth(),canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
}

更新2:

您需要请求运行时权限才能保存和获取图像 首先,您需要将此添加到清单文件

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

接下来,将此方法添加到您的活动中

public static boolean hasPermissions(Context context,String... permissions)
{

    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M && context!=null && permissions!=null){
        for(String permission: permissions){
            if(ActivityCompat.checkSelfPermission(context,permission)!= PackageManager.PERMISSION_GRANTED){
                return  false;
            }
        }
    }
    return true;
}

最后在您的onCreate中添加这些行

int Permission_All = 1;

    String[] Permissions = {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
    if(!hasPermissions(this,Permissions)){
        ActivityCompat.requestPermissions(this,Permissions,Permission_All);
    }
本文链接:https://www.f2er.com/3140408.html

大家都在问