Java Android PDF (Bitmap) is not diplayed at full size - java

I'm trying to show a PDF File in my App but when I show the file, it is not shown at full size, it only covers about 1/4 of the screen.
Here is my code:
public void render() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
final ImageView pdfView = (ImageView) getActivity().findViewById(R.id.pdfView);
pdfView.post(new Runnable() {
#Override
public void run() {
try {
int width = pdfView.getWidth();
int height = pdfView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
System.out.printf("Filename: " + pdfFile.getName());
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY));
if (currentPage < 0) {
currentPage = 0;
} else if (currentPage > renderer.getPageCount()) {
currentPage = renderer.getPageCount() - 1;
}
Matrix m = pdfView.getImageMatrix();
Rect rect = new Rect(0, 0, width, height);
renderer.openPage(currentPage).render(bitmap, rect, m, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
pdfView.setImageMatrix(m);
pdfView.setImageBitmap(bitmap);
pdfView.invalidate();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
When I log the width and the height I get the results: 1440 / 1944

Try setting it as page width and height. Use below code and check
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
PdfRenderer.Page page = renderer.openPage(0);
int pageWidth = page.getWidth();
int pageHeight = page.getHeight();
float scale = Math.min((float) REQ_WIDTH / pageWidth, (float) REQ_HEIGHT / pageHeight);
Bitmap bitmap = Bitmap.createBitmap((int) (pageWidth * scale), (int) (pageHeight * scale), Bitmap.Config.ARGB_8888);
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imageView.setImageBitmap(bitmap);

Related

Saving a canvas larger than the physical screen

I'm dynamically drawing a some Image, Text through custom view where user can move text up/down left/right also zoom in/out but I would like to save the whole view as Image.I know I can save image but I need it to be in a higher resolution than the actual screen I'm capturing it on.
I am saving image using
File file = new File(imagePath);
try {
FileOutputStream out = new FileOutputStream(file, false);
if (parentView != null) {
parentView.setDrawingCacheEnabled(true);
Bitmap drawingCache = saveSettings.isTransparencyEnabled()
? BitmapUtil.removeTransparency(parentView.getDrawingCache())
: parentView.getDrawingCache();
drawingCache.compress(saveSettings.getCompressFormat(), saveSettings.getCompressQuality(), out);
}
out.flush();
out.close();
Log.d(TAG, "Filed Saved Successfully");
return null;
} catch (Exception e) {
FirebaseCrashlytics.getInstance().recordException(e);
e.printStackTrace();
Log.d(TAG, "Failed to save File");
return e;
}
Using above saving functionality image quality is very poor. I need to very high-resolution image.
Please try this way may help you
class MyActivity extends Activity {
private View rootLayoutContainerView;
private int imageWidth;
private int imageHeight;
private int screenLayoutWidth;
private int screenLayoutHeight;
public final void nextToOverlay() {
Bitmap result = Bitmap.createBitmap(this.screenLayoutWidth, this.screenLayoutHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
rootLayoutContainerView.draw(canvas);
result = resizeBitmapFitXY(imageWidth, imageHeight, result);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 100, bytes);
File file = getimagePath((Context)this, "framelayer");
try {
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
} catch (IOException var6) {
var6.printStackTrace();
}
}
public final Bitmap resizeBitmapFitXY(int width, int height,Bitmap bitmap) {
Bitmap background = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
float originalWidth = (float)bitmap.getWidth();
float originalHeight = (float)bitmap.getHeight();
Canvas canvas = new Canvas(background);
float scale = 0.0F;
float xTranslation = 0.0F;
float yTranslation = 0.0F;
if (originalWidth > originalHeight) {
scale = (float)height / originalHeight;
xTranslation = ((float)width - originalWidth * scale) / 2.0F;
} else {
scale = (float)width / originalWidth;
yTranslation = ((float)height - originalHeight * scale) / 2.0F;
}
Matrix transformation = new Matrix();
transformation.postTranslate(xTranslation, yTranslation);
transformation.preScale(scale, scale);
Paint paint = new Paint();
paint.setFilterBitmap(true);
canvas.drawBitmap(bitmap, transformation, paint);
return background;
}
public File getimagePath(Context context,String name) {
File mTranscodeOutputFile = null;
try {
File outputDir = new File(context.getExternalFilesDir(null), "image");
if (!outputDir.exists()) {
outputDir.mkdir();
}
mTranscodeOutputFile = new File(outputDir, name + ".jpg");
} catch (Exception var5) {
}
return mTranscodeOutputFile;
}
}

How to center a vector in an image?

I have the following code:
public class LetterGenerator {
private static final int NUM_OF_TILE_COLORS = 8;
private final TextPaint mPaint = new TextPaint();
private final Rect mBounds = new Rect();
private final Canvas mCanvas = new Canvas();
private final char[] mFirstChar = new char[1];
private final TypedArray mColors;
private final int mTileLetterFontSize;
private final Bitmap mDefaultBitmap;
private final int mWidth;
private final int mHeight;
public LetterGenerator(Context context) {
final Resources res = context.getResources();
mPaint.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
mPaint.setColor(Color.WHITE);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setAntiAlias(true);
mColors = res.obtainTypedArray(R.array.avatar_colors);
mTileLetterFontSize = res.getDimensionPixelSize(R.dimen.tile_letter_font_size);
mDefaultBitmap = drawableToBitmap(ContextCompat.getDrawable(context, R.drawable.ic_person_white_24dp));
mWidth = res.getDimensionPixelSize(R.dimen.letter_tile_size);
mHeight = res.getDimensionPixelSize(R.dimen.letter_tile_size);
}
public Bitmap getCircularLetterTile(String displayName) {
final Bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
final Canvas c = mCanvas;
c.setBitmap(bitmap);
c.drawColor(pickColor(displayName));
if (displayName.trim().length() == 0) {
c.drawBitmap(mDefaultBitmap, dpToPx(4) ,dpToPx(4), null);
} else {
final char firstChar = displayName.trim().charAt(0);
mFirstChar[0] = Character.toUpperCase(firstChar);
mPaint.setTextSize(mTileLetterFontSize);
mPaint.getTextBounds(mFirstChar, 0, 1, mBounds);
c.drawText(mFirstChar, 0, 1, mWidth / 2, mHeight / 2 + (mBounds.bottom - mBounds.top) / 2, mPaint);
}
return getCircularBitmap(bitmap);
}
private Bitmap getCircularBitmap(Bitmap bitmap) {
Bitmap output;
if (bitmap.getWidth() > bitmap.getHeight()) {
output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
} else {
output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
float radius = 0;
if (bitmap.getWidth() > bitmap.getHeight()) {
radius = bitmap.getHeight() / 2;
} else {
radius = bitmap.getWidth() / 2;
}
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(radius, radius, radius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
private static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if (bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
}
It creates an avatar letter. As default it sets an XML vector icon. But the icon is a bit of. I can't seem to figure out which arguments I need to pass on line c.drawBitmap(mDefaultBitmap, dpToPx(4) ,dpToPx(4), null). The dpToPx method is:
private int dpToPx(int dp) {
return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}
What I get:
How can I center the icon?
Change the line
c.drawBitmap(mDefaultBitmap, dpToPx(4) ,dpToPx(4), null);
To:
c.drawBitmap(mDefaultBitmap, mWidth / 2 - mDefaultBitmap.getWidth() / 2, mHeight / 2 - mDefaultBitmap.getHeight() / 2)

How to load a existent bitmap into Picasso

The reason that I'm using Picasso is because I need a rounded image and I could achieve this with Picasso using Transformation:
public class CircleTransform implements Transformation {
#Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap,
BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
#Override
public String key() {
return "circle";
}
}
And then :
Picasso.with(this).load(R.drawable.image)
.transform(new CircleTransform()).into(photo);
But I'm taking a Bitmap from a Camera and I need to put the image inside of ImageView, rounded! I was trying to use Bitmap to File but it doesnt' work!

How to add shadow to a cropped circle image?

I'm using the following to transform an image into a circle. (The purpose is to have a rounded circle image to use as a button in an Android application.)
I'm trying to add a shade of shadow but I can't get it to work. Can anyone help?
public static class CircleTransform extends BitmapTransformation {
public CircleTransform(Context context) {
super(context);
}
#Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
return result;
}
#Override
public String getId() {
return getClass().getName();
}
}

setBitmapImage is not working in panasonic and one plus after image compression

This is the method where i'm setting the bitmap to imageView. This works properly for all the devices except oneplus and panasonic devices. It will show blank when i set the bitmap to imageView in oneplus and panasonic devices and the bitmap is not null. we thought android version might be the issue, but it worked fine for other devices with the same version.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, REQUEST_CAMERA);
ImageView chatImageSendView;
private void onCaptureImageResult(Intent data) {
ImageCompression imageCompressione = new ImageCompression(ChatWithImageActivity.this);
String compressImagePath = imageCompressione.compressImage(fileUri.getPath());
destination = new File(compressImagePath );
Bitmap bmp = null;
try {
bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), fileUri);
} catch (IOException e) {
e.printStackTrace();
}
ExifInterface exifCamera = null;
try {
exifCamera = new ExifInterface(fileUri.getPath());
} catch (IOException e) {
e.printStackTrace();
}
int orientationCam = exifCamera.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap bmRotatedCam = rotateBitmap(bmp, orientationCam);
if (bmRotatedCam != null) {
chatImageSendView.setImageBitmap(bmRotatedCam);
}
}
This class we are using for image compression.
public class ImageCompression {
private Context context;
private static final float maxHeight = 1280.0f;
private static final float maxWidth = 1280.0f;
public ImageCompression(Context context){
this.context=context;
}
public String compressImage(String imagePath) {
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
float imgRatio = (float) actualWidth / (float) actualHeight;
float maxRatio = maxWidth / maxHeight;
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
bmp = BitmapFactory.decodeFile(imagePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.RGB_565);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
if(bmp!=null)
{
bmp.recycle();
}
ExifInterface exif;
try {
exif = new ExifInterface(imagePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream out = null;
String filepath = getFilename();
try {
out = new FileOutputStream(filepath);
//write the compressed bitmap at the destination specified by filename.
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return filepath;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
public String getFilename() {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Medcync/ImageSent");
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
mediaStorageDir.mkdirs();
}
String mImageName="IMG_"+ String.valueOf(System.currentTimeMillis()) +".jpg";
String uriString = (mediaStorageDir.getAbsolutePath() + "/"+
mImageName);;
return uriString;
}
}
Below method is used to rotate the image
public Bitmap rotateBitmap(Bitmap bitmap, int orientation) {
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return bmRotated;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
}
}

Categories

Resources