在我的应用程序中,用户从相机捕获图像或从图库中选择图像,然后将其转换为pdf并将其上传到服务器,现在我的问题是从相机捕获的图像在某些设备上旋转,我确实有代码尝试解决此问题,但是它不起作用
private void PDFCreation(){
PdfDocument document=new PdfDocument();
PdfDocument.PageInfo pageInfo;
PdfDocument.Page page;
Canvas canvas;
int i;
for (i=0; i < list.size(); i++) {
pageInfo=new PdfDocument.PageInfo.Builder(992, 1432, 1).create();
page=document.startPage(pageInfo);
canvas=page.getCanvas();
image=BitmapFactory.decodeFile(list.get(i));
image=Bitmap.createScaledBitmap(image, 980, 1420, true);
image.setDensity(DisplayMetrics.DENSITY_300);
canvas.setDensity(DisplayMetrics.DENSITY_300);
canvas.drawBitmap(image, 0, 0, null);
float rotation=0;
try {
ExifInterface exifInterface=new ExifInterface(selectedPhoto);
int orientation=exifInterface.getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90: {
rotation=-90f;
break;
}
case ExifInterface.ORIENTATION_ROTATE_180: {
rotation=-180f;
break;
}
case ExifInterface.ORIENTATION_ROTATE_270: {
rotation=90f;
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
canvas.rotate(rotation);
document.finishPage(page);
}
@SuppressWarnings("deprecation") String directory_path=Environment.getExternalStorageDirectory().getPath() + "/mypdf/";
File file=new File(directory_path);
if (!file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.mkdirs();
}
@SuppressLint("SimpleDateFormat") String timeStamp=(new SimpleDateFormat("yyyyMMdd_HHmmss")).format(new Date());
String targetPdf=directory_path + timeStamp + ".pdf";
filePath=new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
} catch (IOException e) {
Log.e("main", "error " + e.toString());
Toasty.error(this, "Error making PDF" + e.toString(), Toast.LENGTH_LONG).show();
}
document.close();
任何建议或问题出在哪里,没有错误代码或任何东西
答案 0 :(得分:1)
在drawBitmap之后,您无法旋转画布。您必须先旋转它,然后使用drawBitmap即
float rotation=0;
try {
ExifInterface exifInterface=new ExifInterface(selectedPhoto);
int orientation=exifInterface.getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90: {
rotation=-90f;
break;
}
case ExifInterface.ORIENTATION_ROTATE_180: {
rotation=-180f;
break;
}
case ExifInterface.ORIENTATION_ROTATE_270: {
rotation=90f;
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
canvas.save();
canvas.rotate(rotation);
//canvas is rotated now use drawBitmap
canvas.drawBitmap(image, 0, 0, null);
canvas.restore();