我如何将位图保存到内部存储中?

时间:2019-01-21 04:37:40

标签: android image android-internal-storage

在这里我想将自动生成的qrcode保存到我的内存中。但是,我无法保存图像

我已经尝试了很多代码,但是从base64string到bitmap。但是,我仍然无法保存图片。

这是我的确认。java

private static final int REQUEST_CAMERA_PERMISSION = 200;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_confirmasi);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    ActivityCompat.requestPermissions(this,new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    },REQUEST_CAMERA_PERMISSION);
    if(PendaftaranDokter.message == "null") {
        Date todayDate = Calendar.getInstance().getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("d/M/yyyy");
        String todayString = formatter.format(todayDate);
        msgcin.setText(todayString);
        NoAntrian.setText("xxxxx");
        if(PendaftaranDokterAfterPoli.tgljanjian1.equals(todayString)) {
            //new MedNo(Login.username1).execute();
            new Regno(PendaftaranDokterAfterPoli.medno).execute();
            msgcin.setText("Registrasi");
            NoAntrian.setText("xxxxx");
        }
        else {
            //new MedNo(Login.username1).execute();
            new AppNo(PendaftaranDokterAfterPoli.medno).execute();
            msgcin.setText("Appointment");
            NoAntrian.setText("-");
        }

        medno.setText(PendaftaranDokterAfterPoli.medno);
        namadokter.setText(PendaftaranDokterAfterPoli.parname1);
        politujuan.setText(PendaftaranPoli.servname1);

        try {
            String date = PendaftaranDokterAfterPoli.tgljanjian1;
            SimpleDateFormat format = new SimpleDateFormat("d/M/yyyy");
            Date newDate = format.parse(date);
            format = new SimpleDateFormat("dd MMMM yyyy");
            String date1 = format.format(newDate);
            tanggal.setText(date1);
        }catch (Exception e)
        {
            Toast.makeText(Confirmasi.this,e.toString(),Toast.LENGTH_SHORT).show();
        }
    }
    else
    {
        Date todayDate = Calendar.getInstance().getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("d/M/yyyy");
        String todayString = formatter.format(todayDate);
            if (PendaftaranDokter.tgljanjian.equals(todayString)) {
                //new MedNo(Login.username1).execute();
                new Regno(PendaftaranDokter.medno).execute();
                msgcin.setText("Registrasi");
                NoAntrian.setText("xxxx");
            } else {
                //new MedNo(Login.username1).execute();
                new AppNo(PendaftaranDokter.medno).execute();
                msgcin.setText("Appointment");
                NoAntrian.setText("-");
            }

        medno.setText(PendaftaranDokter.medno);
        namadokter.setText(PendaftaranDokter.parname);
        politujuan.setText(PendaftaranDokter.servname);

        try {
            String date = PendaftaranDokter.tgljanjian;
            SimpleDateFormat format = new SimpleDateFormat("d/M/yyyy");
            Date newDate = format.parse(date);
            format = new SimpleDateFormat("dd MMMM yyyy");
            String date1 = format.format(newDate);
            tanggal.setText(date1);
        }catch (Exception e)
        {
            Toast.makeText(Confirmasi.this,e.toString(),Toast.LENGTH_SHORT).show();
        }
    }

    ok = (ImageView) findViewById(R.id.ok);
    ok.setImageResource(R.drawable.confirmimage);
    ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            OpenMainMenu();
        }
    });
}

private  File getOutputMediaFile(){
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + getApplicationContext().getPackageName()
            + "/Files");

    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    }
    // Create a media file name
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
    File mediaFile;
    String mImageName="MI_"+ timeStamp +".jpg";
    mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
    return mediaFile;
}

private void storeImage(Bitmap image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        Log.d(TAG, "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    }
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }
}

class Regno extends AsyncTask<String, String, String>
{
    private String medno;
    public Regno(String medno) {
        this.medno = medno;
    }
    @Override
    protected String doInBackground(String... strings) {
        CallSoap cs = new CallSoap();
        String medno1 = cs.RegNo(medno);
        return medno1;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            BitMatrix bitMatrix = multiFormatWriter.encode(s, BarcodeFormat.QR_CODE, 200, 200);
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
            img.setImageBitmap(bitmap);
            storeImage(bitmap);
            //saveToInternalStorage(bitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        number.setText(s);
    }
}

class AppNo extends AsyncTask<String, String, String>
{
    private String medno;
    public AppNo(String medno) {
        this.medno = medno;
    }
    @Override
    protected String doInBackground(String... strings) {
        CallSoap cs = new CallSoap();
        String medno1 = cs.AppointNo(medno);
        return medno1;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            BitMatrix bitMatrix = multiFormatWriter.encode(s, BarcodeFormat.QR_CODE, 100, 100);
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
            img.setImageBitmap(bitmap);
            storeImage(bitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }
}

在这里我已经获得了qrcode的位图,我想将qrcode保存到我的内部移动存储中

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码将位图保存到内部存储中。它将在内部存储imageDir中创建目录,并且您必须指定名称来保存图像,即profile.jpg

 private String saveToInternalStorage(Bitmap bitmapImage){
            ContextWrapper cw = new ContextWrapper(getApplicationContext());
             // path to /data/data/yourapp/app_data/imageDir
            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            // Create imageDir
            File mypath=new File(directory,"profile.jpg");

            FileOutputStream fos = null;
            try {           
                fos = new FileOutputStream(mypath);
           // Use the compress method on the BitMap object to write image to the OutputStream
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
            } catch (Exception e) {
                  e.printStackTrace();
            } finally {
                try {
                  fos.close();
                } catch (IOException e) {
                  e.printStackTrace();
                }
            } 
            return directory.getAbsolutePath();
        }

答案 1 :(得分:0)

您是否在AndroidManifest文件中添加了<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

更新: 如果要保存到内部存储,可以使用以下代码:

private void storeImage(Bitmap image) {
    try {
        String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
        String mImageName="MI_"+ timeStamp +".jpg";

        FileOutputStream fos = openFileOutput(mImageName, MODE_PRIVATE);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

它将保存到data / data / your_packagename / files