首页 > 解决方案 > 如何保存新的图像按钮图片并在重新启动时加载新创建的图像按钮图像

问题描述

一旦应用程序关闭,我正在尝试重新加载从我的画廊或相机中的图像按钮中获取的图像

我已经尝试将它保存到一个文件并从该文件加载,但我无法让它工作。




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, 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, 200, 200, 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, 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 完成吗?它可以保存到文件中并从文件中加载吗?

标签: androidandroid-fragmentssaveloadandroid-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();

之后,您将其转换DrawableBitmap

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, 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);
    }

推荐阅读