我试图将图像保存在我的内部存储器中,文件已保存,但它已损坏

时间:2016-10-18 07:26:39

标签: java android image

我从图库中选择图像并尝试将图像保存在内部存储中 文件已保存但看起来已损坏。它没有显示图像 我能知道我现在要做什么吗?

这是我得到的图像: 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();
            }
        }
     }`

2 个答案:

答案 0 :(得分:1)

在OnActivityResult中添加此代码

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

将位图保存到SD卡方法

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

答案 1 :(得分:0)

即使在finalBitmap变量有任何值之前调用saveImage函数,如果在单击ImageView并使用它的绘图缓存时调用以下函数,它可以工作(将路径调整为必需的)。

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