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

原文 标签 java android image

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

这是我得到的图像:


    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();
            }
        }
     }`

最佳答案

在OnActivityResult中添加此代码

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


将位图保存到sdcard方法

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

相关文章:

java - 无法从android.support.v4.app.Fragment转换为android.app.Fragment

android - 在Android中,是否可以在运行时(而不是在清单中)为活动设置“ android:configChanges”?

java - 泽西岛宁静的异常

java - 如何从批处理脚本检查Java安装?

android - 适用于xamarin android的ClearableEdittext

html - 如何在锚标签的标题属性内添加图像标签?

javascript - 如何在Django中使用图片更新div?

html - 打印从CSS Sprite加载的图像?

java - 从远程网站读取JSON文件

java - XPath表达式不起作用