Images loaded from URI have black Background - android

I am trying to load PNG which has transparent background.
mImageCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
ImageThumbnailAdapter.IMAGE_PROJECTION, null, null,
MediaStore.Images.ImageColumns.DISPLAY_NAME);
Projection:
public static final int IMAGE_ID_COLUMN = 0;
public static final int IMAGE_NAME_COLUMN = 1;
Method for loading:
private static Bitmap loadThumbnail(ContentResolver cr, Uri uri) {
return MediaStore.Images.Thumbnails.getThumbnail(
cr, ContentUris.parseId(uri), MediaStore.Images.Thumbnails.MINI_KIND, sBitmapOptions);
}
Setting in View:
Bitmap bitmapOld = loadThumbnail(mArgs.mContentResolver, mArgs.mUri);
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmapOld.compress(Bitmap.CompressFormat.PNG, 100, out );
final Bitmap bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
Bitmap mutableBitmap = bitmapOld.copy(Bitmap.Config.ARGB_8888, true);
final Canvas canvas = new Canvas(mutableBitmap);
// Canvas c = new Canvas(bitmap);
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
//This drawabl is coming black in Background.
final Bitmap bmpfinal = mutableBitmap;

use this code
return MediaStore.Images.Media.getBitmap(context.getContentResolver‌​(), uri);
i hope it may solve your problem...

Picasso will help you out to resolve your issue, go through provided link and integrate picasso.

Related

Print Textviews and webview from fragment

I'm using such code for creating pdf from webview
PrintManager printManager = (PrintManager) this
.getSystemService(Context.PRINT_SERVICE);
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter("PDF");
printManager.print("PDF", printAdapter,
new PrintAttributes.Builder().build());
what should I do, to add to this pdf creation some TextView because I need to add additional fields to my fragment?
Know about itextg, but I need something free.
Choose an option to implement fields as html in webview
You can get a bitmap out of the webview and then draw the textview on the bitmap, using the bitmap canvas.
From there, you can convert the bitmap into a pdf and share the pdf.
Here is the code for converting a webview into a bitmap, and also converting a bitmap into a pdf and then sharing it, asking the user to select its printer app:
public static void sharePdfFile(WebView webView, Context context)
{
Bitmap bitmap = webviewToBitmap( webView );
PrintedPdfDocument pdf = bitmapToPdf( bitmap, context );
File file = pdfToFile( pdf, context );
shareFile( file,"application/pdf", context );
}
private static void shareFile(File file, String contentType, Context context)
{
Uri uri = FileProvider.getUriForFile(
context,
context.getPackageName() + ".fileprovider",
file);
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType(contentType);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Toast.makeText(
context,
"Choose your printer app",
Toast.LENGTH_LONG
).show();
context.startActivity( shareIntent );
}
private static File pdfToFile(PrintedPdfDocument printedPdfDocument, Context context)
{
File file = new File(context.getFilesDir(), "share.pdf");
try {
FileOutputStream outputStream = new FileOutputStream(file);
printedPdfDocument.writeTo(outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
printedPdfDocument.close();
return file;
}
private static PrintedPdfDocument bitmapToPdf(Bitmap bitmap, Context context)
{
PrintAttributes printAttributes = new PrintAttributes.Builder()
.setColorMode(PrintAttributes.COLOR_MODE_COLOR)
.setMediaSize(PrintAttributes.MediaSize.ISO_A4)
.setMinMargins(PrintAttributes.Margins.NO_MARGINS)
.setResolution(new PrintAttributes.Resolution("1", "label", 300, 300))
.build();
PrintedPdfDocument printedPdfDocument = new PrintedPdfDocument(context, printAttributes);
PdfDocument.Page pdfDocumentPage = printedPdfDocument.startPage(1);
Canvas pdfCanvas = pdfDocumentPage.getCanvas();
bitmap = scaleBitmapToHeight(bitmap, pdfCanvas.getHeight());
pdfCanvas.drawBitmap(bitmap, 0f, 0f, null);
printedPdfDocument.finishPage(pdfDocumentPage);
return printedPdfDocument;
}
private static Bitmap webviewToBitmap(WebView webView) {
webView.measure(
View.MeasureSpec.makeMeasureSpec(
0,
View.MeasureSpec.UNSPECIFIED
),
View.MeasureSpec.makeMeasureSpec(
0,
View.MeasureSpec.UNSPECIFIED
)
);
int webViewWidth = webView.getMeasuredWidth();
int webViewHeight = webView.getMeasuredHeight();
webView.layout(0,0, webViewWidth, webViewHeight );
Bitmap bitmap = Bitmap.createBitmap(webViewWidth, webViewHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(bitmap, 0, bitmap.getHeight(), new Paint());
webView.draw(canvas);
return bitmap;
}
private static Bitmap scaleBitmapToHeight(Bitmap bitmap, int maxHeight) {
int height = bitmap.getHeight();
if(height > maxHeight) {
int width = bitmap.getWidth();
float scalePercentage = ((float)maxHeight) / height;
return Bitmap.createScaledBitmap(bitmap, (int) (width * scalePercentage), maxHeight, false);
}
return bitmap;
}

How can I get the absolute path of an image selected from google drive instead of gallery for fixing it's orientation?

In my app, am trying to let the user select an image from the phone storage and display it. Trying to do so, I've faced a problem that the image is returned rotated. So after some search I found some code snippets that helped me to do it right. But testing the same strategy on images selected from google drive or any cloud storage gives an error.
Here are the code snippets I use to get the absolute path and modify the image rotation.
private static String getRealPathFromURI(Context context, Uri uri) {
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
Log.d("here", wholeID);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
Log.d("here", filePath);
return filePath;
}
public static Bitmap modifyOrientation(Bitmap bitmap, String image_absolute_path) throws IOException {
ExifInterface ei = new ExifInterface(image_absolute_path);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotate(bitmap, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotate(bitmap, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotate(bitmap, 270);
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
return flip(bitmap, true, false);
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
return flip(bitmap, false, true);
default:
return bitmap;
}
}
public static Bitmap rotate(Bitmap bitmap, float degrees) {
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
public static Bitmap flip(Bitmap bitmap, boolean horizontal, boolean vertical) {
Matrix matrix = new Matrix();
matrix.preScale(horizontal ? -1 : 1, vertical ? -1 : 1);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
And finally am using the modify method here, after getting a bitmap:
public static String encodeImgToBase64(Uri uri, Context context) throws IOException {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
inputStream.close();
inputStream = context.getContentResolver().openInputStream(uri);
options.inSampleSize = calculateInSampleSize(options, REQUIRED_WIDTH, REQUIRED_HEIGHT);
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(inputStream, null, options);
inputStream.close();
bitmap = modifyOrientation(bitmap, getRealPathFromURI(context, uri));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, byteArrayOutputStream);
byte[] imgByteArray = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
return Base64.encodeToString(imgByteArray, Base64.DEFAULT);
}
So, my question is how to do the same thing on images selected from a cloud storage ?
You can try download the image, save in device tmp storage then you can use same method that you used for gallery image to it.

setImageViewUri doesn't show picture but show background of imageview

File file = new File("/storage/emulated/0/BabyCareData/photo/20160229_161413.jpg");
if (file.exists()) {
views.setImageViewUri(R.id.imageAvatar, Uri.parse(file.getPath()));
}
I have check the path and the uri,it is right.setImageViewUridoesn't show picture but show a white screen(background is white).
Try this:
File file = new File("/storage/emulated/0/BabyCareData/photo/20160229_161413.jpg");
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
views.setImageViewBitmap(R.id.imageAvatar, bitmap);
}
Try this:
File file = new File(/storage/emulated/0/BabyCareData/photo/20160229_161413.jpg);
if(file.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
setBitmap(views,R.id.imageAvatar,myBitmap);
}
private void setBitmap(RemoteViews views, int resId, Bitmap bitmap){
Bitmap proxy = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(proxy);
c.drawBitmap(bitmap, new Matrix(), null);
views.setImageViewBitmap(resId, proxy);
}

How to get Alpha of a Bitmap?

I have two problems.
First I am changing the alpha of a Bitmap and saving it to an ImageView but whenever I am getting the Bitmap from the ImageView it is different to how it looks in the ImageView, the RGB values are Changed.
Second, I am wondering how to get alpha of a bitmap.
imageview=(ImageView)findViewById(R.id.image);
public Bitmap ColorDodgeBlend(Bitmap source, Bitmap layer,int alpha) {
Bitmap base = source.copy(Config.ARGB_8888, true);
Bitmap blend = layer.copy(Config.ARGB_8888, false);
IntBuffer buffBase = IntBuffer.allocate(base.getWidth() * base.getHeight());
base.copyPixelsToBuffer(buffBase);
buffBase.rewind();
IntBuffer buffBlend = IntBuffer.allocate(blend.getWidth() * blend.getHeight());
blend.copyPixelsToBuffer(buffBlend);
buffBlend.rewind();
IntBuffer buffOut = IntBuffer.allocate(base.getWidth() * base.getHeight());
buffOut.rewind();
while (buffOut.position() < buffOut.limit()) {
int filterInt = buffBlend.get();
int srcInt = buffBase.get();
int redValueFilter = Color.red(filterInt);
int greenValueFilter = Color.green(filterInt);
int blueValueFilter = Color.blue(filterInt);
int redValueSrc = Color.red(srcInt);
int greenValueSrc = Color.green(srcInt);
int blueValueSrc = Color.blue(srcInt);
int redValueFinal = colordodge(redValueFilter, redValueSrc);
int greenValueFinal = colordodge(greenValueFilter, greenValueSrc);
int blueValueFinal = colordodge(blueValueFilter, blueValueSrc);
int pixel = Color.argb(alpha, redValueFinal, greenValueFinal, blueValueFinal);
buffOut.put(pixel);
}
buffOut.rewind();
base.copyPixelsFromBuffer(buffOut);
blend.recycle();
return base;
};
bmp=ColorDodgeBlend(Bitmap source, Bitmap layer,alpha); imageview.setImageBitmap(bmp);
But when I try to save bitmap from ImageView, the rgb of saved bitmap is different to how it appears in the ImageView, changing alpha changes the value of rgb.
public Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b
}
bitmap b=loadBitmapFromView(imageview);
saveBitmap(b);
private void saveBitmap(Bitmap bmp) {
try {
File f = new File(Environment.getExternalStorageDirectory()
+ "/Pictures/SketchPhoto/");
f.mkdirs();
Date d = new Date();
CharSequence s = DateFormat
.format("MM-dd-yy hh-mm-ss", d.getTime());
fileName = s.toString() + ".jpeg";
String fullf = f + "/" + fileName;
FileOutputStream fos = new FileOutputStream(fullf);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
Toast.makeText(getApplicationContext(), "Sketch Saved", 100).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
I have done some research and found that it only happens when that value of alpha is smaller than 255.

How to get image from video file

Hi i'm developer in korea. I have some question so i enter this site.
InputStream is;
URL url =
new URL("http://112.216.25.58:8888/VOD_LAUNCHER/media/youtube_sample3.mp4");
Uri uri = Uri.parse(url.toURI().toString());
is = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
//Bitmap bitmap = BitmapFactory.decodeFile(url.toString());
//MediaMetadataRetriever ret = new MediaMetadataRetriever();
//ret.setDataSource(url.toString());
//Bitmap bitmap = ret.getFrameAtTime(0);
//mImageView.setImageURI(uri);
//Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(uri.toString(), Thumbnails.MICRO_KIND);
mImageView.setImageBitmap(bitmap);
private Bitmap getPreview(URI uri) {
File image = new File(uri);
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
return null;
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
//opts.inSampleSize = originalSize / THUMBNAIL_SIZE;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(),
contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I try to use ThumbnailUtil and etc but it didn't work.
How to get ThumbnailImage on android 4.0?
Thanks any reply.
From API level 8 you can just do this:
String path = /*get video path*/;
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
MediaStore.Images.Thumbnails.MINI_KIND);
Nice and simple :)
If you want to extract a frame of a video you should use this class. The code should be something like that:
MediaMetadataRetriever media = new MediaMetadataRetriever();
media.setDataSource(path);
Bitmap extractedImage = media.getFrameAtTime(time, option);
Hope it´s useful
Try This to get Thumbnail of a Video.
ImageView videoview;
Bitmap thumb = ThumbnailUtils.createVideoThumbnail("YOUR VIDEO STRING PATH", MediaStore.Images.Thumbnails.MINI_KIND);
Matrix matrix = new Matrix();
Bitmap bmThumbnail = Bitmap.createBitmap(thumb, 0, 0,
thumb.getWidth(), thumb.getHeight(), matrix, true);
videoview.setImageBitmap(bmThumbnail);
Edited: Use this method to get string path of Video URI.
/**
* Try to return the absolute file path of the Gallery video.
*
* #param context
* #param uri
* #return the file path or null
*/
public static String getVideoPathFromGallary(final Context context,Uri contentUri) {
String[] proj = { MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.DURATION};
Cursor cursor = ((Activity) context).managedQuery(contentUri, proj, null, null, null);
if (cursor == null)
return null;
cursor.moveToFirst();
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
int fileSize = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
long duration = TimeUnit.MILLISECONDS.toSeconds(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)));
System.out.println("size: " + fileSize);
System.out.println("duration: " + duration);
return cursor.getString(column_index);
}
very simple !!! you can use glide library.
first add an imageView on videoView and use the code below:
>
GlideApp.with(getApplicationContext()).load("empty")
.thumbnail(GlideApp.with(getApplicationContext()).load("videoURL"))
.into(imageView);
this code will download an image, and eventually, that leads to less internet consumption.

Categories

Resources