我正在构建一个应用程序来将图像上传到我的公司服务器我现在正在处理拍摄多张图像并将它们转换为 PDF,以便同一文档中的图像可以保持在一起
我的问题是我不知道如何制作它,所以我可以将多个图像添加到 PDF 创建中
目前单个图像有效,但如果我选择多个图像,我会得到空指针异常
主要代码
public class PdfMake extends AppCompatActivity {
private final int PICK_IMAGE=12345;
private final int REQUEST_CAMERA=6352;
CameraPhoto cameraPhoto;
GalleryPhoto galleryPhoto;
String selectedPhoto;
@Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.VmPolicy.Builder builder4=new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder4.build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_make);
Button fromCamera=findViewById(R.id.SelectImages2);
Button PdfMake=findViewById(R.id.button4);
fromCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showPictureDialog();
}
});
PdfMake.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api=Build.VERSION_CODES.KITKAT)
@Override
public void onClick(View v) {
try {
createPdf();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void showPictureDialog () {
AlertDialog.Builder pictureDialog=new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems={
"Select photo from gallery",
"Capture photo from camera"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
getImageFromGallery();
break;
case 1:
try {
getImageFromCamera();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
});
}
@RequiresApi(api=Build.VERSION_CODES.KITKAT)
private void createPdf() throws IOException {
// create a new document
PdfDocument document=new PdfDocument();
// crate a page description
PdfDocument.PageInfo pageInfo=new PdfDocument.PageInfo.Builder(3000, 6000, 1).create();
// start a page
PdfDocument.Page page=document.startPage(pageInfo);
Canvas canvas=page.getCanvas();
Bitmap image=BitmapFactory.decodeFile(selectedPhoto);
canvas.drawBitmap(image, 10, 10, null);
document.finishPage(page);
String directory_path=Environment.getExternalStorageDirectory().getPath() + "/mypdf/";
File file=new File(directory_path);
if (!file.exists()) {
file.mkdirs();
}
String targetPdf=directory_path + "test-2.pdf";
File filePath=new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
Toast.makeText(this, "Done", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e("main", "error " + e.toString());
Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
}
// close the document
document.close();
}
private void getImageFromCamera () throws IOException {
cameraPhoto=new CameraPhoto(getApplicationContext());
Intent in=cameraPhoto.takePhotoIntent();
startActivityForResult(in, REQUEST_CAMERA);
Bungee.split(PdfMake.this);
}
private void getImageFromGallery () {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
Bungee.split(PdfMake.this);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
String photoPath=cameraPhoto.getPhotoPath();
selectedPhoto=photoPath;
try {
Bitmap bitmap=ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
} catch (FileNotFoundException e) {
Toasty.error(getApplicationContext(),
"Something Wrong while loading photos", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == PICK_IMAGE) {
Uri uri=data.getData();
galleryPhoto.setPhotoUri(uri);
String photoPath=galleryPhoto.getPath();
selectedPhoto=photoPath;
try {
Bitmap bitmap=ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
} catch (FileNotFoundException e) {
Toasty.error(getApplicationContext(),
"Something Wrong while choosing photos", Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
int CAMERA_RESULT=11100;
if(requestCode == CAMERA_RESULT){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
try {
getImageFromCamera();
} catch (IOException e) {
e.printStackTrace();
}
}
else{
Toasty.error(getApplicationContext(), "Permission Needed.", Toast.LENGTH_LONG).show();
}
}
else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
if(requestCode == PICK_IMAGE){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
getImageFromGallery();
}
else{
Toasty.error(getApplicationContext(), "Permission Needed.", Toast.LENGTH_LONG).show();
}
}
else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
图库图像的代码
public class GalleryPhoto {
final String TAG = this.getClass().getSimpleName();
private Context context;
private Uri photoUri;
public void setPhotoUri(Uri photoUri) {
this.photoUri = photoUri;
}
public GalleryPhoto(Context context) {
this.context = context;
}
public Intent openGalleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction("android.intent.action.GET_CONTENT");
return Intent.createChooser(intent, this.getChooserTitle());
}
public String getChooserTitle() {
return "Select Pictures";
}
public String getPath() {
String path;
if (VERSION.SDK_INT < 11) {
path = RealPathUtil.getRealPathFromURI_BelowAPI11(this.context, this.photoUri);
} else if (VERSION.SDK_INT < 19) {
path = RealPathUtil.getRealPathFromURI_API11to18(this.context, this.photoUri);
} else {
path = RealPathUtil.getRealPathFromURI_API19(this.context, this.photoUri);
}
return path;
}
}
相机图像代码
public class CameraPhoto {
final String TAG = this.getClass().getSimpleName();
private String photoPath;
private Context context;
public String getPhotoPath() {
return this.photoPath;
}
public CameraPhoto(Context context) {
this.context = context;
}
public Intent takePhotoIntent() throws IOException {
Intent in = new Intent("android.media.action.IMAGE_CAPTURE");
if (in.resolveActivity(this.context.getPackageManager()) != null) {
File photoFile = this.createImageFile();
if (photoFile != null) {
in.putExtra("output", Uri.fromFile(photoFile));
}
}
return in;
}
private File createImageFile() throws IOException {
String timeStamp = (new SimpleDateFormat("yyyyMMdd_HHmmss")).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
this.photoPath = image.getAbsolutePath();
return image;
}
public void addToGallery() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(this.photoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.context.sendBroadcast(mediaScanIntent);
}
}