how to covert image view into bitmap in android studio? - android

Can anyone tell me how to convert imageview to bitmap? In my app, i'm accessing the gallery and getting a bitmap of a picture into an imageview, then using picasso, i'm resizing the images that are too big to directly uploaded to parse. I can resize the image in the image view using picasso but how do i get the bitmap from the image view to upload to parse? this is my code..
public static final int IMAGE_GALLERY_REQUEST = 20;
private ImageView imgPicture;
public Bitmap image;
public void openGallery(View view){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select Picture"),IMAGE_GALLERY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// if we are here, everything processed successfully.
if (requestCode == IMAGE_GALLERY_REQUEST) {
Uri imageUri = data.getData();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(imageUri);
image = BitmapFactory.decodeStream(inputStream);
height= image.getHeight();
h= String.valueOf(height);
width= image.getWidth();
w= String.valueOf(width);
if (width>800 || height>600)
{
Picasso.with(this)
.load(imageUri)
.resize(800,600)
.centerCrop()
.into(imgPicture);
// imgPicture.setImageBitmap(image);
//what should i write here to convert this imageview to bitmap? and then later use that bitmap to upload the image to parse?
}
else
{
//do nothing
imgPicture.setImageBitmap(image);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
// show a message to the user indictating that the image is unavailable.
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
}
}

You only can generate the bitmap from imageview but not in real image size, this generate the bitmap with imageview size
Bitmap bitmap;
try {
bitmap = Bitmap.createBitmap(YOUR_VIEW.getWidth(), YOUR_VIEW.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
YOUR_VIEW.draw(canvas);
File root = Environment.getExternalStoragePublicDirectory(Environment.PICTURES);
String fname = "NAME_OF_FILE.jpg";
file = new File(root, fname);
try {
if (!root.exists()) {
root.mkdir();
}
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
YOUR_VIEW.destroyDrawingCache();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
If you don't wanna save to a file, use this code:
public static Bitmap getScreenViewBitmap(View v) {
v.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false); // clear drawing cache
return b;
}

Related

How do I get thumbnail of a video in android

I want some help in creating thumbnail of a video being recorded from my android phone and I got this code from this Link, and I modified this part of the code to generate the thumbnail but somehow the thumbnail is not being generated, so any help will be appreciated.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == VIDEO_CAPTURED) {
videoFileUri = data.getData();
if (videoFileUri != null) {
Bitmap image= ThumbnailUtils.createVideoThumbnail(videoFileUri.toString(),MODE_APPEND);
ImageView imageView=(ImageView)findViewById(R.id.image);
imageView.setImageBitmap(image);
}
playVideoButton.setEnabled(true);
}
}
You can use glide. its automatically set thumb image of video.
Glide is also able to display the thumbnail of videos, as long as they're stored on the phone. Let's assume you get the file path by letting the user select a video: Based on this document https://futurestud.io/tutorials/glide-displaying-gifs-and-videos
String filePath = "/storage/emulated/0/Pictures/example_video.mp4";
Glide
.with(context)
.asBitmap()
.load(Uri.fromFile(new File(filePath)))
.into(imageViewGifAsBitmap);
Here is the complete tested working solution:
Try it.
if (videoFileUri != null) {
Bitmap bitmapThumb = null;
try {
bitmapThumb = ThumbnailUtils.createVideoThumbnail(videoFileUri.toString(),
MediaStore.Video.Thumbnails.MINI_KIND);// MINI_KIND, size: 512 x 384 thumbnail | MICRO_KIND, size: 96 x 96 thumbnail
ImageView imageView = (ImageView) findViewById(R.id.image);
// imageView.setImageBitmap(bitmapThumb);
Uri uri = getImageUri(context, bitmapThumb);
Picasso.with(context)
.load(uri)
.placeholder(R.drawable.ic_imagedefault)
.error(R.drawable.ic_imagedefault)
.resize(350, 200)//as per need.
.centerCrop()
.into(imageView);
} catch (Exception e) {
e.printStackTrace();
} finally {
bitmapThumb = null;
}
}
}
Here is the static method for getImageUri :
public static Uri getImageUri(Context inContext, Bitmap inImage) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.PNG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
} catch (Exception e) {
e.printStackTrace();
return Uri.parse("");
}
}
Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Video.Thumbnails.MICRO_KIND);
This works fine for me.
https://developer.android.com/reference/android/media/ThumbnailUtils
Uri uri = getImageUri(context, bitmapThumb);
Glide.with(getContext()).
load(uri).
thumbnail(0.1f).
into(imageView);

Share loaded image with glide from imageview

I have a loaded image on my imageview widget which was loaded from glide library. I want to use a share intent to share that image to other applications. I have tried various possibilities without any success. Please help.
public class BookstorePreviewActivity extends AppCompatActivity {
ImageView imageView;
LinearLayout mShare;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookstore_preview);
imageView = findViewById(R.id.image_preview_books);
mShare= findViewById(R.id.download_books);
mShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// fetching image view item from cache
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath());
try {
cachePath.createNewFile();
FileOutputStream outputStream = new FileOutputStream(cachePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// sharing image to other applications (image not found)
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(cachePath));
startActivity(Intent.createChooser(share, "Share via"));
}
});
Just Pass activity context to the takeScreenShot activity it will
work!!!
public static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
//Find the screen dimensions to create bitmap in the same size.
DisplayMetrics dm = activity.getResources().getDisplayMetrics();
int width = dm.widthPixels;
int height = dm.heightPixels;
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
takeScreen(b,activity);
return b;
}
public static void takeScreen(Bitmap bitmap,Activity a) {
//Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "tarunkonda" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
try {
OutputStream fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
openScreenshot(imageFile,a);
}
private static void openScreenshot(File imageFile,Activity activity) {
Intent intent = new Intent(activity,ImageDrawActivity.class);
intent.putExtra(ScreenShotActivity.PATH_INTENT_KEY,imageFile.getAbsolutePath());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}

How do I save the imageview created to camera roll?

In the code below, you can see that I have created an imageview using a bitmap. What I want to know is how I can save an image of that imageview to my camera roll. Thanks!
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.key_code_zoom);
title = (TextView) findViewById(R.id.accountTitleLarge);
imageView = (ImageView) findViewById(R.id.keyCodeLarge);
Intent callingActivity = getIntent();
Bundle callingBundle = callingActivity.getExtras();
if (callingBundle != null) {
String titleText = callingBundle.getString("title");
byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
title.setText(titleText);
imageView.setImageBitmap(bmp);
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
supportFinishAfterTransition();
}
});
}
To save an image in gallery, you must first get the bitmap and then save it.
private void imageToRoll(){
imageView.buildDrawingCache();
Bitmap image = imageView.getDrawingCache(); // Gets the Bitmap
MediaStore.Images.Media.insertImage(getContentResolver(), imageBitmap, imagTitle , imageDescription); // Saves the image.
}
Also, set the permission in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If you are looking for some code that will help you save the Image from the ImageView to your phone storage then the following code will help you
public String getImageFromView() {
imageview.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
imageview.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
imageview.layout(0, 0, imageview.getMeasuredWidth(), imageview.getMeasuredHeight());
imageview.buildDrawingCache(true);
//Define a bitmap with the same size as the view
Bitmap b = imageview.getDrawingCache();
String imgPath = getImageFilename();
File file = new File(imgPath);
try {
OutputStream os = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.JPEG, 90, os);
os.flush();
os.close();
ContentValues image = new ContentValues();
image.put(Images.Media.TITLE, "NST");
image.put(Images.Media.DISPLAY_NAME, imgPath.substring(imgPath.lastIndexOf('/')+1));
image.put(Images.Media.DESCRIPTION, "App Image");
image.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
image.put(Images.Media.MIME_TYPE, "image/jpg");
image.put(Images.Media.ORIENTATION, 0);
File parent = file.getParentFile();
image.put(Images.ImageColumns.BUCKET_ID, parent.toString()
.toLowerCase().hashCode());
image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, parent.getName()
.toLowerCase());
image.put(Images.Media.SIZE, file.length());
image.put(Images.Media.DATA, file.getAbsolutePath());
Uri result = mContext.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imgPath;
}
you will have to provide a file path getImageFilename();this function provides the path where the file is suppose to be stored. The ContentValues will be responsible to let the images be scanned in gallery.
Hope this helps.

Generate bitmap from view

When I get the bitmap from the DrawingCache of a view I get no error but I don't see a valid bitmap either. What am I doing wrong?
The code I use to generate the bitmap:
SharePhotoView sharePhotoView = SharePhotoView_.build(this);
sharePhotoView.bind(mCatch);
sharePhotoView.setDrawingCacheEnabled(true);
sharePhotoView.buildDrawingCache();
Bitmap bitmap = sharePhotoView.getDrawingCache();
catchImage.setImageBitmap(bitmap);
The code I use to make the view:
#EViewGroup(R.layout.share_photo)
public class SharePhotoView extends LinearLayout{
#ViewById
ImageView catchImage;
public SharePhotoView(Context context) {
super(context);
}
public void bind(Catch catchItem) {
Bitmap bitmap = BitmapFactory.decodeFile(catchItem.getImage().getPath());
catchImage.setImageBitmap(bitmap);
}
}
Use this code for a Bitmap from view:
Bitmap bitmap;
try {
bitmap = Bitmap.createBitmap(YOUR_VIEW.getWidth(), YOUR_VIEW.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
YOUR_VIEW.draw(canvas);
File root = Environment.getExternalStoragePublicDirectory(Environment.PICTURES);
String fname = "NAME_OF_FILE.jpg";
file = new File(root, fname);
try {
if (!root.exists()) {
root.mkdir();
}
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
YOUR_VIEW.destroyDrawingCache();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
Found a method somewhere that did the trick:
public static Bitmap getScreenViewBitmap(View v) {
v.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false); // clear drawing cache
return b;
}
Source: http://www.jattcode.com/getting-bitmap-from-a-view-visible-invisible-oncreate/

Facing Image Uploading and retrieving difficulties to Datastore in android?

I have searched but for some answers but may be my fault couldn't find my desired answer.Now below what i am trying:
I am trying to upload an image like of a status or a post or any profile pic.Profile pic will be small and status or any post image will be big. Now what i want to do:
1. I am converting the image to string text and uploading it to datastore and it's limit is 1Mbyte.So i want to check while uploading image that it doesn't cross limit.
2. I want to check that the image is of png format.If it is not then won't upload.Show a Toast.Can i convert image there?? :(
3. If user is uploading image of suppose 700kbyte but the profile pic is small i.e 100kbyte will be enough for profile pic then i can compress the pic to my defined size and then upload it to datastore.It may remain 700kbyte if it is for status image.
I am converting image to string and uploading it to datastore and again converting back to image while showing it in my app.My code:
public static String imageToStringConverter(Bitmap image){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String imageToString = Base64.encodeToString(byteArray, Base64.NO_WRAP);
return imageToString;
}
public static Bitmap stringToimageConverter(String imageString){
byte[] stringTobyte = Base64.decode(imageString, Base64.NO_WRAP);
Bitmap bmp = BitmapFactory.decodeByteArray(stringTobyte, 0, stringTobyte.length);
return bmp;
}
Now the problem i am facing
:
1.When i am uploading the image it is taking time.So should i use asynctask while uploading after converting the image to my desired size??
2.When i first enter into my app ,i have shown profile pic i.e if i log into my account it will fetch an image for profile from datastore.But it is taking much time and my log in seems to be lengthy.
I have solved my problem by reducing the image.
Here is my code:
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
Uri imageUri;
try {
imageUri = imageReturnedIntent.getData();
}catch(Exception e){
Toast.makeText(getActivity(),"Image Not Found",Toast.LENGTH_SHORT).show();
return;
}
//final InputStream imageStream = getActivity().getContentResolver().openInputStream(imageUri);
//final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
ShrinkBitmapConverter sh = new ShrinkBitmapConverter(getActivity());
Bitmap selectedImage = null;
try {
selectedImage = sh.shrinkBitmap(imageUri,450,350);
} catch (Exception e) {
Toast.makeText(getActivity(),"Image Not Found",Toast.LENGTH_SHORT).show();
}
statusImage = ImageConverter.imageToStringConverter(selectedImage);
if(statusImage.length()>512000){
Toast.makeText(getActivity(),"Image is too big",Toast.LENGTH_LONG).show();
}else {
postImage.setImageBitmap(selectedImage);
}
}
}
ImageConverter.java:
public class ImageConverter {
public static String imageToStringConverter(Bitmap image){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String imageToString = Base64.encodeToString(byteArray, Base64.NO_WRAP);
return imageToString;
}
public static Bitmap stringToimageConverter(String imageString){
byte[] stringTobyte = Base64.decode(imageString, Base64.NO_WRAP);
Bitmap bmp = BitmapFactory.decodeByteArray(stringTobyte, 0, stringTobyte.length);
return bmp;
}
}
ShrinkBitmapConverter.java:
public class ShrinkBitmapConverter {
Context context;
public ShrinkBitmapConverter(Context c){
context=c;
}
public Bitmap shrinkBitmap(Uri uri,int width,int height) throws FileNotFoundException {
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = null;;
try {
bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri),null,bmpFactoryOptions);
int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);
if (heightRatio > 1 || widthRatio > 1)
{
if (heightRatio > widthRatio)
{
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri),null,bmpFactoryOptions);
} catch (Exception e) {
Toast.makeText(context,"Image Not Found",Toast.LENGTH_SHORT).show();
}
return bitmap;
}
}

Categories

Resources