Android Java copyFile不适用于Gallery Image

时间:2016-11-18 11:24:21

标签: java android

我有一个小相机应用程序将图像存储到图片文件夹:

File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "preview.jpg");

稍后我想复制此Image并使用新的Filename保存它。因此我使用了这里找到的复制功能:

private void copyFile(File sourceFile, File destFile) throws IOException {
    if (!sourceFile.exists()) {
        return;
    }

    FileChannel source = null;
    FileChannel destination = null;
    source = new FileInputStream(sourceFile).getChannel();
    destination = new FileOutputStream(destFile).getChannel();
    if (destination != null && source != null) {
        destination.transferFrom(source, 0, source.size());
    }
    if (source != null) {
        source.close();
    }
    if (destination != null) {
        destination.close();
    }
}

这里调用copyFile:

        // OLD FILE
        File oldFile = new File(imageUri.getPath());

        // NEW FILE
        File newFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test123.jpg");

        // COPY FILE
        copyFile(oldFile,newFile);

但它什么也没做。也没有异常或其他东西。我做错了什么?

编辑:完整代码

public class ParticipateActivity extends AppCompatActivity {

private static String logtag = "Camera APP";
private static int TAKE_PICTURE = 1;
private Uri imageUri;
private Bitmap cameraImage;
static final String appDirectoryName = "album name";
static final File imageRoot = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), appDirectoryName);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    imageRoot.mkdirs();
    verifyStoragePermissions(this);
    setContentView(R.layout.activity_participate);

    Button cameraButton = (Button) findViewById(R.id.camera_button);
    Button saveButton = (Button) findViewById(R.id.save_button);
    cameraButton.setOnClickListener(cameraListener);
    saveButton.setOnClickListener(saveListener);
}

private View.OnClickListener cameraListener = new View.OnClickListener() {
    public void onClick(View v) {
        takePhoto(v);
    }
};

private View.OnClickListener saveListener = new View.OnClickListener() {
    public void onClick(View v) {
        try {
            savePhoto(v);
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(logtag,"Error copying file!");
        }
    }
};

private void takePhoto(View v) {
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    File photo = new File(imageRoot, "preview.jpg");
    //Log.e(logtag,"test");
    imageUri = Uri.fromFile(photo);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(intent, TAKE_PICTURE);
}

private Boolean copyFile(File sourceFile, File destFile) throws IOException {
    if (!sourceFile.exists()) {
        //Log.e(logtag,sourceFile.getAbsolutePath());
        return false;
    } else {
        //Log.e(logtag,sourceFile.getAbsolutePath());
    }

    FileChannel source = null;
    FileChannel destination = null;
    source = new FileInputStream(sourceFile).getChannel();
    destination = new FileOutputStream(destFile).getChannel();
    if (destination != null && source != null) {
        try {
            destination.transferFrom(source, 0, source.size());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        //source.transferTo(0, source.size(), destination);
        Log.e(logtag,"transfer started");
    }
    if (source != null) {
        source.close();
    } else {return false;}
    if (destination != null) {
        destination.close();
        return true;
    } else {return false;}
}

private void savePhoto(View v) throws IOException {
    EditText input_name = (EditText) findViewById(R.id.input_name);
    EditText input_mail = (EditText) findViewById(R.id.input_mail);
    EditText input_phone = (EditText) findViewById(R.id.input_phone);
    String name = input_name.getText().toString();
    String mail = input_mail.getText().toString();
    String phone = input_phone.getText().toString();

    if (name.length() != 0 && mail.length() != 0) {
        if (phone.length() == 0) {
            phone = "NoPhone";
        }
        // set fileName
        String fileName = name + "-" + mail + "-" + phone;
       // Log.e(logtag,fileName);

        // OLD FILE
        File oldFile = new File(imageUri.getPath());
        //Log.e(logtag,"Path: " + imageUri.getPath());

        // NEW FILE
        File newFile = new File(imageRoot, "test123.jpg");
        Log.e(logtag,"path: " + newFile.getAbsolutePath());

        // COPY FILE
        if(oldFile.exists()) {
            Boolean copied = copyFile(oldFile,newFile);
            Log.e(logtag,copied.toString());

            // log text
            if(copied) Toast.makeText(ParticipateActivity.this, "Gespeichert!", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(ParticipateActivity.this, "Konnte nicht gespeichert werden! Kein Foto?", Toast.LENGTH_LONG).show();
        }
    } else {
        Toast.makeText(ParticipateActivity.this, "Bitte Name und Email ausfüllen!", Toast.LENGTH_LONG).show();
    }
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (resultCode == Activity.RESULT_OK) {
        Uri selectedImage = imageUri;
        getContentResolver().notifyChange(selectedImage, null);

        ImageView imageView = (ImageView) findViewById(R.id.image_camera);
        ContentResolver cr = getContentResolver();
        Bitmap bitmap;

        try {
            bitmap = MediaStore.Images.Media.getBitmap(cr, selectedImage);
            imageView.setImageBitmap(bitmap);

            // Change height of image
            android.view.ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
            layoutParams.height = (int) getResources().getDimension(R.dimen.imageView_height);
            imageView.setLayoutParams(layoutParams);

            // Hide Label and Button
            TextView uploadText = (TextView) findViewById(R.id.upload_text);
            uploadText.setVisibility(View.GONE);
            Button uploadButton = (Button) findViewById(R.id.camera_button);
            uploadButton.setVisibility(View.GONE);

            // Show Image Name
            //Toast.makeText(ParticipateActivity.this,selectedImage.toString(),Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(logtag, e.toString());
        }
    }
}

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
 * Checks if the app has permission to write to device storage
 * <p>
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

}

0 个答案:

没有答案