简体   繁体   中英

I tried to save image in my internal storage the file is saved but it hows damaged

I pick the image from gallery and tried to save the image in my internal storage.
The file is saved but it looks damaged. It is not showing the image.
Can I know what I have to do now?

Here is image I got:这是我得到的图像

    public class ImageUpload extends android.app.Fragment
    {
        ImageView image;
        String img_str;


        Button upload;

        Bitmap finalBitmap;

        private static final int CONTENT_REQUEST=1337;
        private File output=null;

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
            View v=inflater.inflate(R.layout.activity_imageupload,container,false);
            image=(ImageView)v.findViewById(R.id.image);
            upload=(Button)v.findViewById(R.id.upload);



           /* Bitmap bitmap = image.getDrawingCache();*/
            image.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    Intent i = new Intent();
                    i.setAction(Intent.ACTION_PICK);
                    i.setType("image/*");
                    i.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(
                            Intent.createChooser(i, "Select Picture"), 1);

                       save Image();
                       }
            });
            image.buildDrawingCache();
           finalBitmap = image.getDrawingCache();

            return v;
        }
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub
            if (resultCode == MainActivity.RESULT_OK) {
                if (requestCode == 1) {
                    Uri selectedImageUri = data.getData();
                    selectedImagePath = getPath(selectedImageUri);
                    System.out.println("Image Path : " + selectedImagePath);
                    image.setImageURI(selectedImageUri);
                    image.setDrawingCacheEnabled(true);

                }
                else if (requestCode == CONTENT_REQUEST) {
                    if (resultCode == 1337) {
                        Intent i=new Intent(Intent.ACTION_VIEW);

                        i.setDataAndType(Uri.fromFile(output), "image/jpeg");
                        startActivity(i);
                        getActivity().finish();
                    }
                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
        public String getPath(Uri uri) {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = getActivity().getContentResolver().query(uri,
                    projection, null, null, null);
            if (cursor == null)
                return null;
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String s = cursor.getString(column_index);
            cursor.close();

            return s;
        }
        public String image() {
            image.buildDrawingCache();
            finalBitmap = image.getDrawingCache();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
            byte[] image = stream.toByteArray();
            System.out.println("byte array:" + image);

            img_str = Base64.encodeToString(image, 0);
            Toast.makeText(getActivity(), img_str, Toast.LENGTH_LONG).show();
            System.out.println("string:" + img_str);
            return null;
        }
     private void save Image() {

            String root = Environment.getExternalStorageDirectory().toString();
            File myDir = new File(root + "/hello_images");
            myDir.mkdirs();
            Random generator = new Random();
            int n = 10000;
            n = generator.nextInt(n);
            String fname = "Image-"+ n +".jpg";
            File file = new File (myDir, fname);
            if (file.exists ()) file.delete ();
            try {
                FileOutputStream out = new FileOutputStream(file);
                finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
     } catch (Exception e) {
                e.printStackTrace();
            }
        }
     }`

Add this code in OnActivityResult

 Bitmap bmp = BitmapFactory.decodeFile(image_path);
        thumb.setImageBitmap(bmp);
saveImageFile(bmp);

Save Bitmap to sdcard Method

 public String saveImageFile(Bitmap bitmap) {
        FileOutputStream out = null;
        String filename = getFilename();
        try {
            out = new FileOutputStream(filename);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return filename;
    }


  private String getFilename() {
        File file = new File(Environment.getExternalStorageDirectory()
                .getPath(), "TestFolder");
        if (!file.exists()) {
            file.mkdirs();
        }
        String uriSting = (file.getAbsolutePath() + "/"
                + System.currentTimeMillis() + ".jpg");
        return uriSting;
    }

You are calling the saveImage function even before the finalBitmap variable has any value, If you call the below function when you click the ImageView with it's drawing cache, It could work ( adjust the path as required).

public File WriteBmpToFile(Bitmap bmp) {
        String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/.kyc";

        File dir = new File(file_path);
        if (!dir.exists())
            dir.mkdirs();
        File file = new File(dir, "kyc_" + Calendar.getInstance().getTimeInMillis() + ".jpg");

        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {

            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return file;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM