I am using glide to load image in image view but it is taking lot of time to show the image in image view. I am loading the picture from my custom camera in the image view. Every thing is working but it takes a lot of time to load the image here is the code:
private void show_image_from_custom_camera(byte[] data) {
bitmap_image = BitmapFactory.decodeByteArray(data, 0, data.length);
ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap_image.compress(Bitmap.CompressFormat.JPEG, 70, stream);
int screenWidth = width;
int screenHeight = height;
Glide.with(this)
.load(data)
.asBitmap().centerCrop()
.into(new SimpleTarget<Bitmap>(width,height) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
// you can do something with loaded bitmap here
// .....
int w = resource.getWidth();
int h = resource.getHeight();
// Setting post rotate to 90
Matrix mtx = new Matrix();
mtx.postRotate(90);
// Rotating Bitmap
Bitmap realImage = Bitmap.createBitmap(resource, 0, 0, w, h, mtx, true);
photo_setter.setImageBitmap(realImage); //setting the image in image-view
}
});
}
Is there anything that will reduce this time? I want to show image in image view at a faster rate.
Thanks to Belzebub .Well I am have made a serious mistake and I forgot to remove the first 3 line of the code that are :
bitmap_image = BitmapFactory.decodeByteArray(data, 0, data.length);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap_image.compress(Bitmap.CompressFormat.JPEG, 70, stream);
Without them everything is working fine and I am loading image in image view with faster speed now I am keeping this post so that anyone wants to load image in image view on Camera.PictureCallback can use this code without the top 3 lines.
Related
In Android Studio I can use the following lines of code to get an array from Bitmap
Bitmap bitmap = get_Image();
Bitmap resizeBitmap = getResizedBitmap(bitmap);
int[] iArr = new int[(resizeBitmap.getWidth() * resizeBitmap.getHeight())];
resizeBitmap.getPixels(iArr, 0, resizeBitmap.getWidth(), 0, 0, resizeBitmap.getWidth(), resizeBitmap.getHeight());
Here is the resizer function:
public Bitmap getResizedBitmap(Bitmap bitmap) {
if (576 == bitmap.getWidth() && 1024 == bitmap.getHeight()) {
return bitmap;
}
Bitmap createBitmap = Bitmap.createBitmap(576, 1024, Config.RGB_565);
Matrix scaledMatrix = scaledMatrix(bitmap.getWidth(), bitmap.getHeight(), createBitmap.getWidth(), createBitmap.getHeight());
new Canvas(createBitmap).drawBitmap(bitmap, scaledMatrix, null);
return createBitmap;
}
However when I convert that int array back to bitmap the image is wrong
Bitmap bmp = Bitmap.createBitmap(1024, 576, Config.RGB_565);
bmp.setPixels(iArr, 0, 1024, 0, 0, 1024, 576);
textViewToChange.setText("Bitmap created");
This is the image when i save it to a file or display it https://imgur.com/a/ZQ0DJAy The above image is how it looks like and below is how it should had looked like
If i read the incorrect image in python, the RGB pixels are placed exactly where they should be like in the correct image but the image dosen't look the same. Why? How can i fix this?
I am getting strange issue of White blank screen when i try to set image inside my image view after scaling it from bitmap.
I am getting random size images from server , I just need to show them in my image view without loose in quality of image. i have taken one layout and add image view dynamically through code.
Here is what i am doing in code :-
Getting Url form server and scaling it accordingly :-
url="http://www.petstory.co/attached_king_photos/hotel/7/attached_d67e2689e0d3370f7e76b5bba9f8e875e42a2e39.jpg"
AsyncTask task = new AsyncTask<String, String, Bitmap>() {
Bitmap bitmap = null;
#Override
protected Bitmap doInBackground(String... params) {
bitmap = getBitmapFromURL(params[0]);
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result.getHeight() > 7000){
getResizedBitmap(result, 4000, 4000, image);
}else{
getResizedBitmap(result, 800, 800, image);
}
}
}.execute(imageUrl);
public Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight, final ImageView image) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = bm.getWidth();
int height = bm.getHeight();
final int wantedgeightis = newHeight;
float scaleWidth = metrics.scaledDensity;
float scaleHeight = metrics.scaledDensity;
// float scaleWidth = ((float) newWidth) / width;
// float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
matrix.setRectToRect(new RectF(0, 0, bm.getWidth(), bm.getHeight()), new RectF(0, 0, newWidth, newHeight), Matrix.ScaleToFit.CENTER);
final Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
// final Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
//
if (wantedgeightis == 4000) {
image.setScaleType(ImageView.ScaleType.FIT_XY);
image.setImageBitmap(resizedBitmap);
} else {
int bitmapWidth = resizedBitmap.getWidth();
int bitmapHeight = resizedBitmap.getHeight();
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, bitmapHeight);
image.setLayoutParams(params);
image.setPadding(10, 0, 10, 0);
image.setScaleType(ImageView.ScaleType.FIT_XY);
image.setImageBitmap(resizedBitmap);
}
}
});
return resizedBitmap;
}
The Url of image which i am setting in above methods is :-
http://www.petstory.co/attached_king_photos/hotel/7/attached_d67e2689e0d3370f7e76b5bba9f8e875e42a2e39.jpg
i am testing on nexus , rest images are aprearing as expected but only this image displays me white blank screen
I even make use of Glide and pisacco getting same issue for this image or sometimes highly distorted image get appear on screen.
Here is the code of Glide which i used :-
Glide.with(this) //passing context
.load(imageUrl) //passing your url to load image.
.placeholder(R.drawable.petzview_logo) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
.error(R.drawable.petz_test)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is.
.diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast.
.fitCenter()//this method help to fit image into center of your ImageView
.dontAnimate()
.override(700, 4000)
.into(image);
I Even tried with bellow code too :-
Glide.with(this)
.load(imageUrl)
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.placeholder(R.drawable.petzview_logo)
.dontAnimate()
.fitCenter()
.into(new ViewTarget<ImageView, GlideDrawable>(image) {
#Override
public void onResourceReady(GlideDrawable resource, GlideAnimation anim) {
Toast.makeText(HowAboutHere.this, "success", Toast.LENGTH_LONG).show();
image.setImageDrawable(resource.getCurrent());
}
#Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
Toast.makeText(HowAboutHere.this, "Glide image load failed for %s -> %s" + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
image.setVisibility(View.INVISIBLE);
}
});
By using .override(700, 4000) , the image is getting displayed but streched and if i change value to .override(700, 4100) , then blank white screen start getting displayed due to very large image size
Or Should i First Save image from URL to any file and then retrieve the image from file and apply inSample size bitmap algo on it this will be time taking and with utilize more memory and make application slow.As mentioned in below two links :-
Best method to download image from url in Android
Strange out of memory issue while loading an image to a Bitmap object
However here i am also posting the image look like when i use Bitmap code form displaying huge image from URL
As you can see the image is still getting stretched.
Any help will be appreciated
Thanks!!!
I want to get the picture of the view(not ImageView) inside,but the picture I got was not clear,Of course the original picture is clear ,here is my codes
public static Bitmap getDrawBitmap(View designView){
designView.destroyDrawingCache();
designView.setDrawingCacheEnabled(true);
designView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
return designView.getDrawingCache();
}
I have tried to scale the View,and then getDrawingCache(),but it didn't work,the view's size didn't change
Bitmap bitmap=ImgUtils.getDrawBitmap(testBtn);
float w=1260f;
float h=1660f;
float x= w/(bitmap.getWidth()/DrawAttribute.density);
float y= h/(bitmap.getHeight()/DrawAttribute.density);
Log.e("x-y",x+"-"+y);
Bitmap result=Bitmap.createBitmap(1260,1660,Bitmap.Config.ARGB_8888);
Canvas offScreen = new Canvas(result);
Matrix matrix=new Matrix();
matrix.setScale(x,y);
offScreen.drawBitmap(bitmap, matrix, null);
//存储路径
OutputStream stream = null;
try {
if (LiApplication.creatDir()) {
stream = new FileOutputStream(Environment.getExternalStorageDirectory()+ "/yc/img/"
+ "save.png");
}
} catch (FileNotFoundException e) {
}
Bitmap.CompressFormat format = Bitmap.CompressFormat.PNG;
result.compress(format, 100, stream);
This is a Demo code for taking screen shot of whole View.
View v = (View) findViewById(R.id.myView);
Bitmap mybitmap = Bitmap.createBitmap(
v.getChildAt(0).getWidth(),
v.getChildAt(0).getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(mybitmap);
iv.getChildAt(0).draw(c);
//remember here View may be any view including ScrollView or what ever it may be.
saveBitmap(bitmap);
Hope this will help. Thanks
I'm writing a custom printing app in Android and I'm looking for ways to save on memory. I have three basic rectangles I need to print on a full page. Currently I'm creating a base Bitmap the size of the page:
_baseBitmap = Bitmap.createBitmap(width/_scale, height/_scale, Bitmap.Config.ARGB_8888);
The print process requests a Rect portion of that page. I cannot predetermine the dimensions of this Rect.
newBitmap = Bitmap.createBitmap(fullPageBitmap, rect.left/_scale, rect.top/_scale, rect.width()/_scale, rect.height()/_scale);
return Bitmap.createScaledBitmap(newBitmap, rect.width(), rect.height(), true);
Using bitmap config ARGB_8888 _baseBitmap is about 28MB (8.5"x11" # 300dpi = 2250*3300*4bytes). Even at 50% scaling (used above), my image is over 7MB. Scaling any smaller than this and image quality is too poor.
I've attempted to create _baseBitmap using Bitmap.Config.RGB_565, which does greatly reduce the full image size, but then when I overlay an image (jpegs) I get funny results. The image is compressed in width, duplicated next to itself, and all the color is green.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = true;
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap myBitmap = BitmapFactory.decodeStream(input, null, options);
input.close();
return myBitmap;
....
private static Bitmap overlay(Bitmap bmp1, Bitmap bmp2, float left, float top) {
Canvas canvas = new Canvas(bmp1);
canvas.drawBitmap(bmp2, left, top, null);
return bmp1;
}
I know I can compress an image of these dimensions down to a reasonable size. I've looked into Bitmap.compress, but for some reason beyond my understanding I'm getting the same size image back:
ByteArrayOutputStream os = new ByteArrayOutputStream();
_baseBitmap.compress(Bitmap.CompressFormat.JPEG, 3, os);
byte[] array = os.toByteArray();
Bitmap newBitmap = BitmapFactory.decodeByteArray(array, 0, array.length);
_baseBitmap.getAllocationByteCount() == newBitmap.getAllocationByteCount()
It would be better to create it compressed than to create a large one and then compress it. Is there any way to create a compressed Bitmap? Any advice is greatly appreciated.
note: Not an Android expert. I'm not necessarily familiar with the platform specific terms you may use to respond. Please be gentle.
Try something like this, if you have a target size in mind.
private static final int MAX_BYTES_IMAGE = 4194304; // 4MB
//...
ByteArrayOutputStream out;
int quality = 90;
do
{
out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);
quality -= 10;
} while (out.size() > MAX_BYTES_IMAGE_FILESIZE);
out.close();
I want that load images from sdcard to listview but i dont need image in big size. size 60dip * 60dip is Sufficient. i am using below codes in thread but however this is slow.i need load images in fast way.
public Bitmap loadImage(String imagePath){
//load bitmap in real size
Bitmap bmp = BitmapFactory.decodeFile(imagePath);
int width = bmp.getWidth();
int height = bmp.getHeight();
//determine size and scale
float newWidth = convertDipToPixel(60, getApplicationContext());//60 dip
float scale = ((float) newWidth) / width;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scale, scale);
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);
return resizedBitmap;}
check android query and image loading using android query
its really fast, try it.
File file = new File(path);
//load image from file, down sample to target width of 300 pixels
aq.id(R.id.avatar).image(file, 300);
you can also use Android-Universal-Image-Loader
String imageUri = "file:///mnt/sdcard/image.png"; // from SD card
// Load image, decode it to Bitmap and display Bitmap in ImageView (or any other view
// which implements ImageAware interface)
imageLoader.displayImage(imageUri, imageView);