Android 图板之保存图像

(1)为了能适应多种屏幕尺寸的手机,我们在创建图像的时候就要根据用户手机屏幕的宽高像素来创建。

(2)该软件将把图形保存到sdcard中,在保存之前,需要检测sdcard是否存在,是否可写入。如通过以上检查,就保存图像。

首先,我们应该检测sdcard的状态,如果不可写入,则给出提示:

    public void saveBitmap()
    {
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state))
        {
            saveToSdcard();
        }
        else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
        {
            Toast.makeText(this.context,
                    getResources().getString(R.string.tip_sdcard_is_read_only),
                    Toast.LENGTH_LONG).show();
        }
        else
        {
            Toast.makeText(
                    this.context,
                    getResources().getString(
                            R.string.tip_sdcard_is_not_available),
                    Toast.LENGTH_LONG).show();
        }
    }

当sdcard存在且可写入时,我们就把图像保存到sd卡中:

    private void saveToSdcard()
    {
        File sdcard_path = Environment.getExternalStorageDirectory();
        String myFloder = getResources().getString(
                R.string.folder_name_in_sdcard);
        File paintpad = new File(sdcard_path + "/" + myFloder + "/");
        try
        {
            if (!paintpad.exists())
            {
                paintpad.mkdirs();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        String timeStamp = (DateFormat.format("yyyy.MM.dd.hh.mm.ss",
                new java.util.Date())).toString();
        String suffixName = ".png";

        String fullPath = "";
        fullPath = sdcard_path + "/" + myFloder + "/" + timeStamp + suffixName;
        try
        {
            Toast.makeText(this.context,
                    getResources().getString(R.string.tip_save_to) + fullPath,
                    Toast.LENGTH_LONG).show();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100,
                    new FileOutputStream(fullPath));
        }
        catch (FileNotFoundException e)
        {
            Toast.makeText(
                    this.context,
                    getResources().getString(R.string.tip_sava_failed)
                            + fullPath, Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }
原文地址:https://www.cnblogs.com/zhujiabin/p/4189804.html