Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/218.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在存储和库中,此代码不会显示图像_Android_Image - Fatal编程技术网

Android 在存储和库中,此代码不会显示图像

Android 在存储和库中,此代码不会显示图像,android,image,Android,Image,我正在使用此代码保存图像。图像保存在具有SD卡插槽的设备中。但是像三星SM-J710F这样只有内存或设备存储器的设备并没有保存图像 我的代码: private void saveImageAsJpeg() { Bitmap bitmap = _paintView.getDrawingCache(); Date d = new Date(); CharSequence s = DateFormat.format("yyyyMMdd-HHmmss", d.getTime())

我正在使用此代码保存图像。图像保存在具有SD卡插槽的设备中。但是像三星SM-J710F这样只有内存或设备存储器的设备并没有保存图像

我的代码:

private void saveImageAsJpeg() {
    Bitmap bitmap = _paintView.getDrawingCache();
    Date d = new Date();
    CharSequence s = DateFormat.format("yyyyMMdd-HHmmss", d.getTime()); // MM-dd-yy hh-mm-ss
    File file = new File(Environment.getExternalStorageDirectory(),"/dcim/MyImageFolder/"+ s + ".jpg");
    Toast.makeText(getApplicationContext(), "Your Image Saved at " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
    try {
    if (!file.exists()) {
            //file.createNewFile();
            file.getParentFile().mkdirs();
         }
        FileOutputStream ostream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
        ostream.close();
        if (file.toURI() != null)
          {
            new MediaScannerNotifier(FillColorActivity.this, file.toString(), MIME_PNG);
          }
        } catch (Exception e) {
        e.printStackTrace();
    }
   }

我已经在堆栈上查看了多个解决方案,但没有得到正确的解决方案。

尝试此示例,希望这对您有所帮助。按一下按钮,呼叫selectpic

public void selectpic() {
    final Dialog myDialog = new Dialog(this);
    myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    myDialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT);
    myDialog.setContentView(R.layout.custom_dialog);
    myDialog.setTitle("Choose Picture");
    Button btncamera = (Button) myDialog.findViewById(R.id.btncamera);
    Button btngallery = (Button) myDialog.findViewById(R.id.btngallery);

    //EnableRuntimePermission();

    //Select Camera
    btncamera.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            ClickImageFromCamera() ;
            myDialog.cancel();
        }
    });

    //Select image from gallery
    btngallery.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            GetImageFromGallery();
            myDialog.cancel();
        }
    });
    myDialog.show();
}

public void ClickImageFromCamera() {
    CamIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    File sdCardDirectory = new File(Environment.getExternalStorageDirectory(),
            "MyFolder/Media/Profile");
    sdCardDirectory.mkdirs();

    File image = new File(sdCardDirectory, "tempProfilepic" + ".jpg");
    uri = Uri.fromFile(image);
    CamIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);
    CamIntent.putExtra("return-data", true);
    startActivityForResult(CamIntent, AppConstants.REQUEST_CAMERA);
}

public void GetImageFromGallery(){
    Intent intent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.setType("image/*");
    //intent.setAction(Intent.ACTION_GET_CONTENT);
    try {
        intent.putExtra("return-data", true);
        startActivityForResult(Intent.createChooser(intent,
                "Complete action using"), AppConstants.SELECT_FILE);

    } catch (ActivityNotFoundException e) {

    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK){
        if (requestCode == AppConstants.REQUEST_CAMERA) {
            ImageCropFunction();
        }
        else if (requestCode == AppConstants.SELECT_FILE) {
            if (data != null) {
                String path = data.getDataString();
                uri = Uri.parse(path);
                Bitmap photo = null;
                try {
                    photo = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //External sdcard location
                File sdCardDirectory = new File(Environment.getExternalStorageDirectory(),
                        "MyFolder/Media/Profile");
                sdCardDirectory.mkdirs();
                File finalimage = new File(sdCardDirectory, "tempProfilepic"+ ".jpg");

                boolean success = false;
                FileOutputStream outStream;
                try {
                    outStream = new FileOutputStream(finalimage);
                    photo.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                    outStream.flush();
                    outStream.close();
                    success = true;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (success) {
                    uri = Uri.fromFile(finalimage);
                    ImageCropFunction();
                }
            }

        }else if (requestCode == AppConstants.CROP_FILE) {
            if (data != null) {
                fileselected = true;
                String path = data.getDataString();
                if (path != null){
                    uri = Uri.parse(path);
                }else{
                    uri = uri;
                    //Bundle extras = data.getExtras();
                    //Bitmap selectedBitmap = extras.getParcelable("data");
                }

                Bitmap bitmap = null;
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                btnprofilepic.setImageBitmap(bitmap);
                File sdCardDirectory = new File(Environment.getExternalStorageDirectory(),
                        "MyFolder/Media/Profile");
                sdCardDirectory.mkdirs();

                File finalimage = new File(sdCardDirectory, "Profilepic"+currentDateandTime+ ".jpg");

                File tempimage = new File(sdCardDirectory, "tempProfilepic" + ".jpg");
                if (tempimage.exists()) {
                    tempimage.delete();
                }
                boolean success = false;
                FileOutputStream outStream;
                try {
                    outStream = new FileOutputStream(finalimage);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                    outStream.flush();
                    outStream.close();
                    success = true;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (success) {
                    selectedfile = finalimage.toString();

                } else {
                    //app.showToast("Error during image saving");
                }
            }
        }
    }
}

public void ImageCropFunction() {
    try {
        CropIntent = new Intent("com.android.camera.action.CROP");
        CropIntent.setDataAndType(uri, "image/*");
        CropIntent.putExtra("crop", "true");
        CropIntent.putExtra("outputX", 500);
        CropIntent.putExtra("outputY", 500);
        CropIntent.putExtra("aspectX", 1);
        CropIntent.putExtra("aspectY", 1);
        CropIntent.putExtra("scale", true);
        startActivityForResult(CropIntent, AppConstants.CROP_FILE);
    } catch (ActivityNotFoundException e) {

    }
}//Image Crop Code End Here
*********************自定义对话框XML文件******************

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/White"
android:gravity="center"
android:orientation="vertical"
android:padding="25dp">

<TextView
    android:id="@+id/txtheader"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="15dp"
    android:text="Select an Image to upload"
    android:textColor="@color/Black"
    android:textSize="16sp"
    android:textStyle="normal" />

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@color/White" />


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:layout_marginRight="5dp"
        android:orientation="vertical">

        <Button
            android:id="@+id/btncamera"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Take Photo"
            android:textColor="@color/White"
            android:textSize="14dp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:layout_marginLeft="5dp"
        android:orientation="vertical">

        <Button
            android:id="@+id/btngallery"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="From Gallery"
            android:textColor="@color/White"
            android:textSize="14dp" />
    </LinearLayout>
</LinearLayout>

如果要在SD卡中将视图另存为图像,可以尝试以下方法:

public static void saveMyView(View view, Context context) {
    Date d = new Date();
    CharSequence fileName = DateFormat.format("yyyyMMdd-HHmmss", d.getTime()); // MM-dd-yy hh-mm-ss

    final File file;

    if(isExternalStorageReadable()) {
        file = new File(Environment.getExternalStorageDirectory().getPath(), "MyImageFolder/");
    } else {
        file  = new File(context.getFilesDir().getPath(), "MyImageFolder/");
    }

    if (!file.exists()) {
        file.mkdir();
    }

    saveBitmapInFile(new File(file.getAbsoluteFile(), fileName + ".jpg"), getBitmapFromView(view), context);
}

public static boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
            Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

private static void saveBitmapInFile(File file, Bitmap bitmap, Context context) {
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(file);

        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private static Bitmap getBitmapFromView(View view) {

    view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

    view.buildDrawingCache();

    Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
            Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(bitmap);
    canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);

    Drawable drawable = view.getBackground();
    if (drawable != null)
        drawable.draw(canvas);

    view.draw(canvas);

    return bitmap;
}

什么是paintView?ImageView?@Abhishek它是View类的对象,我从中获取位图。如果文件不存在,则您正在创建目录。那看起来是胡说八道。此外,你没有检查mkdirs的返回值。作为android的新手,我不知道该怎么做。请指导我文件输出流的尝试捕获在哪里?startActivityForResultIntent.CreateSchooseContent,使用AppConstants.SELECT_文件完成操作;此lineAppConstant中的AppConstants是一个java类文件,我在其中声明值为101的SELECT_文件。谢谢,但我的代码在sd卡存储中运行良好。。但不适用于devicephone/内部存储。如果设备中没有安装sd卡,我想将其保存到设备中解决方案。我试过了,但在没有sd卡的设备上仍然不起作用。在上面的代码中,如果sd卡没有安装,它将存储在内部内存context.GetFileDir中。但是没有安装sd卡的设备没有存储图像是的,我告诉你,如果我们使用context.GetFileDir,我们可以在任何文件夹中看到它