我正面临一个我不理解的问题。我正在拍照,然后按照下面的代码创建一个PNG图像文件,但是在该行的某个地方,一个随机字符串被添加到文件名中,这引起了我各种各样的问题。例如(根据我发现的教程):创建一个名为dimage_(生成的时间戳记)的图像,并将字符串保存为共享首选项,并将图像保存在getExternalFilesDir(Environment.DIRECTORY_PICTURES)
中。在共享首选项中,字符串是正确的,但是文件中附加了上述字符串。
例如: 生成的文件名字符串保存在共享首选项中:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="driver_picture">dimage_20190610_065509</string>
</map>
使用adb检查的文件结果为:
127|generic_x86:/storage/emulated/0/Android/data/africa.mykagovehicledrivers/files/Pictures $ ls
dimage_20190610_0655091215099619.png
generic_x86:/storage/emulated/0/Android/data/africa.mykagovehicledrivers/files /Pictures $
我不知道1215099619
多余部分来自哪里!
这是活动的代码:
package africa.mykagovehicledrivers;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.yalantis.ucrop.UCrop;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class RegisterDriverImage extends AppCompatActivity {
String currentPhotoPath;
final int REQUEST_TAKE_PHOTO = 1;
final int CAMERA_PERMISSIONS = 3;
Activity activity = this;
ImageView imgTakePicture, imgDriver;
Button btnContinueDriver;
ProgressBar prgImage;
SharedPreferences prefs;
SharedPreferences.Editor edit;
String imageFileName;
Tools t;
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good so launch take picture from here
dispatchTakePictureIntent();
} else {
// Permission denied. Warn the user and kick out of app
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.permsDeniedCameraTitle);
builder.setMessage(R.string.permsDeniedCameraMessage);
builder.setCancelable(false);
builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
});
builder.create().show();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Uri starturi = Uri.fromFile(new File(currentPhotoPath));
Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
UCrop.Options options = AppConstants.setUcropOptions(activity);
UCrop.of(starturi, destinationuri).withOptions(options).start(activity);
}
// On result from cropper add to image view
if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
prgImage.setVisibility(View.VISIBLE);
final Uri resultUri = UCrop.getOutput(data);
assert resultUri != null;
File imgFile = new File(resultUri.getPath());
Picasso.Builder builder = new Picasso.Builder(getApplicationContext());
builder.listener(new Picasso.Listener() {
@Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
builder.build().load(imgFile).into(imgDriver, new Callback() {
@Override
public void onSuccess() {
Log.d("-------->", "onSuccess: CROPPED!");
prgImage.setVisibility(View.INVISIBLE);
btnContinueDriver.setEnabled(true);
}
@Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_driver_image);
prefs = getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
edit = prefs.edit();
imgTakePicture = findViewById(R.id.imgTakePicture);
imgDriver = findViewById(R.id.imgDriver);
btnContinueDriver = findViewById(R.id.btnContinueDriver);
prgImage = findViewById(R.id.prgImage);
t = new Tools(getApplication(), getApplicationContext(), this);
imgTakePicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
imgDriver.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
btnContinueDriver.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edit.putString("driver_picture", imageFileName);
edit.putString("nextstep", "drivinglicense");
edit.apply();
Intent drivinglicense = new Intent(getApplicationContext(), RegisterDrivingLicense.class);
startActivity(drivinglicense);
finish();
}
});
// Always ask for camera permissions
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.CAMERA }, CAMERA_PERMISSIONS);
}
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("IMAGE CREATION FAILED", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"africa.mykagovehicledrivers.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
imageFileName = "dimage_" + timeStamp;
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".png",
storageDir
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
}
根据代码,我使用String imageFileName;
保存路径,然后在按钮单击操作中使用它以将其保存到共享首选项中。
谢谢!
答案 0 :(得分:0)
找出原因。 createTempFile执行此操作。切换到新的File()即可解决此问题。