Crop a surface view in Android - android

Here's what I need:
I have a Surface view that has a square (image view) on top of it. I need to capture an image, and crop out the area that was visible only within the square.
This code gives me decent results but specific only to some devices:
int width=(int)(bitmap.getWidth()*60/100);
int height=(bitmap.getHeight()*100/100); //dont change
bitmap=Bitmap.createBitmap(bitmap,150,0, width-55, height);
Is there any way I could generalize this code? Is there any other way to get what I need?
EDIT: This is how I got it to work-
Save the image from the surface view as a bitmap (This is very simple. There are many examples available on the internet that show how to do that)
Use this code in a function, and call it after the image is clicked
//bitmap is the object where the image is stored
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int left;
if(width > height){
left = (width - height)/2;
}
else {
left = (height - width)/2;
}
bitmap=Bitmap.createBitmap(bitmap,left,0, height, height);

Related

preview stretches in camera2 apis

Following are the screenshots when using texture view in camera2 apis.In full screen the preview stretches,but it works when using lower resolution(second image).
How to use this preview in full screen without stretching it.
Below answer assumes you are in portrait mode only.
Your question is
How to use the preview in full-screen without stretching it
Let's break it down to 2 things:
You want the preview to fill the screen
The preview cannot be distorted
First you need to know that this is logically impossible without crop, if your device's viewport has a different aspect ratio with any available resolution the camera provides.
So I would assume you accept cropping the preview.
Step 1: Get a list of available resolutions
StreamConfigurationMap map = mCameraCharacteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
throw new IllegalStateException("Failed to get configuration map: " + mCameraId);
}
Size[] sizes = map.getOutputSizes(SurfaceTexture.class);
Now you get a list of available resolutions (Sizes) of your device's camera.
Step 2: Find the best aspect ratio
The idea is to loop the sizes and see which one best fits. You probably need to write your own implementation of "best fits".
I am not going to provide any code here since what I have is quite different from your use case. But ideally, it should be something like this:
Size findBestSize (Size[] sizes) {
//Logic goes here
}
Step 3: Tell the Camera API that you want to use this size
//...
textureView.setBufferSize(bestSize.getWidth(), bestSize.getHeight());
Surface surface = textureView.getSurface();
try {
mPreviewRequestBuilder = mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.addTarget(surface);
mCamera.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
mSessionCallback, null);
} catch (final Exception e) {
//...
}
Step 4: Make your preview extends beyond your viewport
This is then nothing related to the Camera2 API. We "crop" the preview by letting the SurfaceView / TextureView extends beyond device's viewport.
First place your SurfaceView or TextureView in a RelativeLayout.
Use the below to extend it beyond the screen, after you get the aspect ratio from step 2.
Note that in this case you probably need to know this aspect ratio before you even start the camera.
//Suppose this value is obtained from Step 2.
//I simply test here by hardcoding a 3:4 aspect ratio, where my phone has a thinner aspect ratio.
float cameraAspectRatio = (float) 0.75;
//Preparation
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int screenWidth = metrics.widthPixels;
int screenHeight = metrics.heightPixels;
int finalWidth = screenWidth;
int finalHeight = screenHeight;
int widthDifference = 0;
int heightDifference = 0;
float screenAspectRatio = (float) screenWidth / screenHeight;
//Determines whether we crop width or crop height
if (screenAspectRatio > cameraAspectRatio) { //Keep width crop height
finalHeight = (int) (screenWidth / cameraAspectRatio);
heightDifference = finalHeight - screenHeight;
} else { //Keep height crop width
finalWidth = (int) (screenHeight * cameraAspectRatio);
widthDifference = finalWidth - screenWidth;
}
//Apply the result to the Preview
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) cameraView.getLayoutParams();
lp.width = finalWidth;
lp.height = finalHeight;
//Below 2 lines are to center the preview, since cropping default occurs at the right and bottom
lp.leftMargin = - (widthDifference / 2);
lp.topMargin = - (heightDifference / 2);
cameraView.setLayoutParams(lp);
If you don't care about the result of Step 2, you can actually ignore Step 1 to Step 3 and simply use a library out there, as long as you can configure its aspect ratio. (It looks like this one is the best, but I haven't tried yet)
I have tested using my forked library. Without modifying any code of my library, I managed to make the preview fullscreen just by using Step 4:
Before using Step 4:
After using Step 4:
And the preview just after taking a photo will not distort as well, because the preview is also extending beyond your screen.
But the output image will include area that you cannot see in the preview, which makes perfect sense.
The code of Step 1 to Step 3 are generally referenced from Google's CameraView.
That's a common problem on some devices. I've noticed it mostly on samsung. You may use a trick with setting transformation on your TextureView to make it centerCrop like ImageView behaviour
I also faced similar situation, but this one line solved my problem
view_finder.preferredImplementationMode = PreviewView.ImplementationMode.TEXTURE_VIEW
in your xml:
<androidx.camera.view.PreviewView
android:id="#+id/view_finder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
For camera implementation using cameraX you can refer
https://github.com/android/camera-samples/tree/master/CameraXBasic
I figured out what was your poroblem. You were probably trying something like this:
textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int j) {
cam.startPreview(surfaceTexture, i, j);
cam.takePicture();
}
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) { }
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) { return false; }
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { }
});

Android ImageView topCrop/bottomCrop scaletype?

I have a square ImageView which displays pictures of varying dimensions. I want to always maintain the original aspect ratio of the pictures and have no margin around the image (so that the image takes up the whole ImageView). For this, I am using the centerCrop scaleType on the ImageView. However, I want to make it so that if the top and bottom of the image are cut off (i.e.: the image is taller than it is wide), the image gets pulled towards the bottom of the container. So instead of having equal amounts of pixels cropped at the top and bottom, the image is flush with the top and sides of the ImageView and the bottom of the image has twice as much cropped off. Is this possible in xml, if not, is there a java solution?
You won't be able to do that with a regular ImageView and it's properties in xml. You can accomplish that with a proper scaleType Matrix, but tbh writing it is a pain in the ass. I'd suggest you use a respected library that can handle this easily. For example CropImageView.
You probably can't do this in layout. But it's possible with a piece of code like this:
final ImageView image = (ImageView) findViewById(R.id.image);
// Proposing that the ImageView's drawable was set
final int width = image.getDrawable().getIntrinsicWidth();
final int height = image.getDrawable().getIntrinsicHeight();
if (width < height) {
// This is just one of possible ways to get a measured View size
image.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int measuredSize = image.getMeasuredWidth();
int offset = (int) ((float) measuredSize * (height - width) / width / 2);
image.setPadding(0, offset, 0, -offset);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
image.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
image.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
}
Note that if your ImageView has predefined size (likely it has) then you need to put this size to dimen resources and the code will be even simpler:
ImageView image = (ImageView) findViewById(R.id.image2);
// For sure also proposing that the ImageView's drawable was set
int width = image.getDrawable().getIntrinsicWidth();
int height = image.getDrawable().getIntrinsicHeight();
if (width < height) {
int imageSize = getResources().getDimensionPixelSize(R.dimen.image_size);
int offset = (int) ((float) imageSize * (height - width) / width / 2);
image.setPadding(0, offset, 0, -offset);
}
See also:
findViewById()
getResources()

SIze Imageview Placeholders

I am using recyclerview with imageviews in each cell.Each imageview loads images from the web and can be square or with more width than height or more height than width i.e any sizes.I am going to display a placeholder for each image while it loads in the background(with a progressbar).But the problem is the dimension of the images is unknown and I want to size the placeholders exactly the size of the images like the 9gag app in which the placeholders are exactly the size of the images while loading in the bacground.How do I achieve this in android ?I don't want to use wrap-content(produces a jarring effect after the image has been downloaded) or a specific height to the imageviews(crops the images).I am using UIL and currently planning to switch to Fresco or Picassa.
In case that your placeholder is just filled of some color, you can easily emulate a color drawable with exactly the same size.
/**
* The Color Drawable which has a given size.
*/
public class SizableColorDrawable extends ColorDrawable {
int mWidth = -1;
int mHeight = -1;
public SizableColorDrawable(int color, int width, int height) {
super(color);
mWidth = width;
mHeight = height;
}
#Override public int getIntrinsicWidth() {
return mWidth;
}
#Override public int getIntrinsicHeight() {
return mHeight;
}
}
To use it with Picasso:
Picasso.with(context).load(url).placeholder(new SizableColorDrawable(color, width, height)).into(imageView);
Now some tips on the ImageView:
public class DynamicImageView extends ImageView {
#Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable drawable = getDrawable();
if (drawable == null) {
super.onMeasure(widthSpecureSpec, heightMeasureSpec);
return;
}
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int reqWidth = drawable.getIntrinsicWidth();
int reqHeight = drawable.getIntrinsicHeight();
// Now you have the measured width and height,
// also the image's width and height,
// calculate your expected width and height;
setMeasuredDimension(targetWidth, targetHeight);
}
}
Hope this will help someone..
If you use fresco, you need to pass the width and height of your image from the web server, then you set the layout params of your drawee view with that width and height.
Like this:
RelativeLayout.LayoutParams draweeParams =
new RelativeLayout.LayoutParams(desiredImageWidthPixel,
desiredImageHeightPixel);
yourDraweeView.setLayoutParams(draweeParams);
From width and height of the image that you pass from your web server, you can calculate/resize proportionally the view as you need. Where desiredImageWidthPixel is the calculated image width that you want to show in yourDraweeView and desiredImageHeightPixel is the calculated image height that you want to show in yourDraweeView.
Don't forget to call
yourDraweeView.getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.FIT_XY);
To make yourDraweeView match the actual params that you set before.
Hope this helps
You can feed image dimensions along with the image url. (I assume you are getting image list from a source, like a JSON file or something.) And resize the ImageView holder inside the RecyclerView according to their dimension and then fire the image downloading process.

Android move ImageView to a specific pixel color

I made a treasure map in photoshop and I made a transparent image with coloured hotspots to put over the treasure map so I can make it clickable.
When I click on the colored dots (that are invisible), Android detects the color clicked and does the appropriate methods, just as asked.
Now I have an imageview, that would be my player, and each day I want it to move to another colored hotspot on the map (each hotspot represents a day of the week).
I have this code, but the position is way off:
private void moveToColor(ImageView iv, int toColor) {
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.hotspots);
int width = bm.getWidth();
int height = bm.getHeight();
int[] pixels = new int[width * height];
bm.getPixels(pixels, 0, width, 0, 0, width, height);
for (int ix = 0; ix < width; ++ix) {
for (int iy = 0; iy < height; ++iy) {
if (toColor == bm.getPixel(ix, iy)) {
iv.animate().translationX((float)ix);
iv.animate().translationY((float)iy);
return;
}
}
}
}
sometimes it will move the imageview close to the toColor, and other times it is completely off or not even on the map.
Any pointers on how I could do this. I tried it with a buffer copypixelstobuffer, but I didn't understand very well how that works. Because above is quite slow..
Thanks!
Sure it is off, read the description of the translationX property carefully: http://developer.android.com/reference/android/view/View.html#attr_android:translationX
"This value is added post-layout to the left property of the view"
It's relative to the left of the view, i.e. it's displacement, not absolute position.
Instead, use
iv.animate().x((float)ix);
and it's twin brother .y()
I actually found that if I change
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.hotspots);
int width = bm.getWidth();
int height = bm.getHeight();
to this:
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.hotspots);
bm = Bitmap.createScaledBitmap(bm,size.x, size.y, true);
int width = bm.getWidth();
int height = bm.getHeight();
where size.x and size.y come from
display = getWindowManager().getDefaultDisplay();
size = new Point();
display.getSize(size);
Then the position is not that far off. It is still not completely where I want it, the player is positioned on the bottom of the dot, but at least it is a step closer.

Use ZXing camera decoding confusion

I check the Internet and see using ZXing to solve two-dimension code. But the code I do not understand.
PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource( data, width, height, dstLeft, dstTop, dstWidth,dstHeight, false);
What the meaning of the parameter?
I went to read the ZXing source code and I found the following (There was no constructor with boolean parameter in the end)
PlanarYUVLuminanceSource(byte[] yuvData, int dataWidth, int dataHeight, int left,
int top, int width, int height)
{
super(width, height);
if (left + width > dataWidth || top + height > dataHeight)
{
throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
}
this.yuvData = yuvData;
this.dataWidth = dataWidth;
this.dataHeight = dataHeight;
this.left = left;
this.top = top;
}
When I read the code I understand the following (I have an assumption that the relevant data consider only as the area of the inner rectangle of where the QR code should be placed in the image).
byte[] yuvData - The byte array that contain the data of the image. All the data the one inside the rectangle and outside of it.
int dataWidth - The width of the data. The width of the data all the area outside and inside the rectangle.
int dataHeight - The Height of the data. The height of the data all the area outside and inside the rectangle.
int left - The left border of the rectangle. Or, how many pixels are outside of the rectangle from the left.
int top - The top border of the rectangle. Or, how many pixels are outside of the rectangle from the top.
int width - The width of the inner rectangle.
int height - The height of the inner rectangle.

Categories

Resources