For some reason I can't for the life of me figure out why this is happening, but I have an imageView where I resize the image pragmatically using a matrix but it won't display the changes until I reapply them in an onTouch event.
So the function of this Activity is to open a gallery picker immediately and then display the result in an imageView where you can pan and resize the image. Then the drawing cache is saved to storage as a bitmap.
I resize the ImageView pragmatically so that it's square so I have to resize the image to match the new dimensions. But it's always displayed as just center until I tap the screen.
here's my code pleas help me
public class PickPic extends Activity {
private static final String D = "PickPic";
float scaleAmount = 1;
//this view determines what part of the image will be kept
ImageView cropView;
Bitmap b;
ScaleGestureDetector scaleD;
//for touch event handling
float initX,initY;
//cropview image matrix
Matrix matC;
int resultCode;
float scale;
//cropview image matrix translation values
float cropTransX, cropTransY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_pic);
resultCode = getIntent().getIntExtra("result code", MainActivity.PICK_PIC_4_PIC_ONE);
scaleD = new ScaleGestureDetector(this, new ScaleListener());
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
cropView = (ImageView) findViewById(R.id.editor);
cropView.setDrawingCacheEnabled(true);
//make crop view square
cropView.getLayoutParams().height = cropView.getWidth();
cropView.requestLayout();
if (resultCode == RESULT_OK) {
try {
b = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
cropView.setImageBitmap(b);
} catch (IOException e) {
e.printStackTrace();
}
}
setValues();
}
private void setValues() {
matC = cropView.getImageMatrix();
//scale crop to fit
matC = scale(matC,b.getWidth(),b.getHeight(),cropView.getWidth(),cropView.getWidth());
float[] matCValues = new float[9];
matC.getValues(matCValues);
//transformation values to be kept for onTouch methods
scale = matCValues[Matrix.MSCALE_X];
cropTransX = matCValues[Matrix.MTRANS_X];
cropTransY = matCValues[Matrix.MTRANS_Y];
cropView.setImageMatrix(matC);
cropView.invalidate();
//here the values get set properly but the display doesn't change
}
private Matrix scale(Matrix mat, float bwidth, float bheight, float vwidth, float vheight) {
float scale;
float dx = 0, dy = 0;
if (bwidth * vheight > vwidth * bheight) {
scale = vheight / bheight;
dx = (vwidth - bwidth * scale) * 0.5f;
} else {
scale = vwidth / bwidth;
dy = (vheight - bheight * scale) * 0.5f;
}
mat.setTranslate(Math.round(dx), Math.round(dy));
mat.preScale(scale, scale);
//mat.setScale(scale, scale);
//mat.postTranslate(Math.round(dx), Math.round(dy));
return mat;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
scaleD.onTouchEvent(event);
switch (MotionEventCompat.getActionMasked(event)){
case (MotionEvent.ACTION_DOWN):
initX = event.getX();
initY = event.getY();
return true;
case (MotionEvent.ACTION_MOVE):
//this is where the display gets updated
matC.setTranslate(cropTransX + event.getX() - initX, cropTransY + event.getY() - initY);
matC.preScale(scale*scaleAmount, scale*scaleAmount);
cropView.setImageMatrix(matC);
cropView.invalidate();
matB.setTranslate(backTransX + event.getX() - initX, backTransY + event.getY() - initY);
matB.preScale(scale*scaleAmount, scale*scaleAmount);
return true;
case (MotionEvent.ACTION_UP):
//commit transformations
cropTransX += event.getX() - initX;
cropTransY += event.getY() - initY;
backTransX += event.getX() - initX;
backTransY += event.getY() - initY;
return true;
default:
return super.onTouchEvent(event);
}
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
scaleAmount *= detector.getScaleFactor();
return true;
}
}
}
Make some delay when called setValues() method in onActivityResult() like below.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
cropView = (ImageView) findViewById(R.id.editor);
cropView.setDrawingCacheEnabled(true);
//make crop view square
cropView.getLayoutParams().height = cropView.getWidth();
cropView.requestLayout();
if (resultCode == RESULT_OK) {
try {
b = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
cropView.setImageBitmap(b);
} catch (IOException e) {
e.printStackTrace();
}
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
setValues();
}
},1500);
}
let me know the result if not working.
Related
I am working on a video player app. But when I am scaling for video zoom, So this app is not cropping in the center in some devices but this code working fine on other devices.
please help me. Or give me any suggestions. Thank you
here is my code
final static float move = 200;
float ratio = 1.0f;
int hasDist;
float baseRatio;
int position = -1;
VideoView videoView;
Uri uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video__player_);
videoView = findViewById(R.id.videoView);
position = getIntent().getIntExtra("position", -1);
String path = videoList.get(position).getPath();
uri = Uri.parse(path);
videoView.setVideoPath(path);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getPointerCount()==2){
int action = event.getAction();
int mainAction = action&MotionEvent.ACTION_MASK;
if (mainAction ==MotionEvent.ACTION_POINTER_DOWN){
hasDist=getDistion(event);
baseRatio = ratio;
}else {
float scale = (getDistion(event)-hasDist)/move;
float fatcher = (float)Math.pow(2,scale);
ratio = Math.min(1024.0f,Math.max(0.0f,baseRatio*fatcher));
videoView.setScaleX(ratio);
videoView.setScaleY(ratio);
}
}
return true;
}
private int getDistion(MotionEvent event) {
int dx = (int) (event.getX(0) - event.getX(1));
int dy = (int) (event.getY(0) - event.getY(1));
return (int) (Math.sqrt(dx * dx + dy * dy));
}
}
after take image from camera this image rotate with tow different degree between front camera and back camera I tried add rotation to image after take image from camera but it doesn't work with all devices by the same degree .
Note : I added face recognition but it doesn't work when images rotate,this is my code .
public class CheckIn extends AppCompatActivity {
private ImageView camera;
String encoded = "";
byte[] byteArray;
static final int REQUEST_IMAGE_CAPTURE = 1;
private Button checkIn;
ContentValues values;
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
Uri imageUri;
Bitmap thumbnail;
SparseArray<Face> faces ;
Matrix matrix ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_in);
camera = (ImageView) findViewById(R.id.camera);
checkIn = (Button) findViewById(R.id.submit);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
});
checkPermissionREAD_EXTERNAL_STORAGE(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
if(Build.VERSION.SDK_INT >= 27) {
//only api 27 above
matrix = new Matrix();
matrix.postRotate(90);
}else{
//only api 27 down
matrix = new Matrix();
matrix.postRotate(270);
}
Bitmap rotatedBitmap = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap converetdImage = getResizedBitmap(rotatedBitmap, 700);
converetdImage.compress(Bitmap.CompressFormat.PNG, 10, byteArrayOutputStream);
byteArray = byteArrayOutputStream.toByteArray();
encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
RequestOptions options = new RequestOptions()
.centerCrop()
.placeholder(R.mipmap.ic_launcher_round)
.error(R.mipmap.ic_launcher_round);
Paint myRectPaint = new Paint();
myRectPaint.setStrokeWidth(5);
myRectPaint.setColor(Color.RED);
myRectPaint.setStyle(Paint.Style.STROKE);
Bitmap tempBitmap = Bitmap.createBitmap(rotatedBitmap.getWidth(), rotatedBitmap.getHeight(),
Bitmap.Config.RGB_565);
Canvas tempCanvas = new Canvas(tempBitmap);
tempCanvas.drawBitmap(rotatedBitmap, 0, 0, null);
FaceDetector faceDetector
= new
FaceDetector.Builder(getApplicationContext()).setTrackingEnabled(false)
.build();
Frame frame = new Frame.Builder().setBitmap(rotatedBitmap).build();
faces = faceDetector.detect(frame);
for (int i = 0; i < faces.size(); i++) {
Face thisFace = faces.valueAt(i);
float x1 = thisFace.getPosition().x;
float y1 = thisFace.getPosition().y;
float x2 = x1 + thisFace.getWidth();
float y2 = y1 + thisFace.getHeight();
tempCanvas.drawRoundRect(new RectF(x1, y1, x2, y2), 2, 2, myRectPaint);
}
Glide.with(CheckIn.this).load(tempBitmap).apply(options)
.into(camera);
} catch (Exception e) {
e.printStackTrace();
} }
}
public void checkPermissionREAD_EXTERNAL_STORAGE(
final Context context) {
// Enable if permission granted
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED) {
}
// Else ask for permission
else {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
}
thanks in advance .
try this please
i just have to add
camera.setDisplayOrientation(90);
now the display is on the right angle.
I want to implement zoom function while video recording in android.But, I am not able to access Camera parameters or Camera startSmoothZoom() method in neither main activity nor surface class. If you access camera parametera in media recorder method(prepareMediaRecorder()) it will throw null pointer exception.
this activity class- in prepareMediaRecorder() method not able to access camera parameters and also not able to set startSmoothZoom(). here camera object giving null pointer exception.
public class CustomCameraPreview extends BaseActivity implements
OnClickListener, AlertPositiveListener, OrientationListener,
ActivityCompat.OnRequestPermissionsResultCallback {
RelativeLayout mLayout;
MediaRecorder mediaRecorder;
private PictureCallback mPictureCallback = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
cameraData = data;
captureAngle = getRotation();
mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
catch (OutOfMemoryError e){
System.gc();
mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
// int rotation=getRotation();
Matrix matrix = new Matrix();
matrix.postRotate(getRotation());
/*mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(),
mBitmap.getHeight(), matrix, true);*/
mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(),
mBitmap.getHeight(), matrix, false);
if (mBitmap != null) {
mButtonRetake.setEnabled(true);
} else {
Message.displayToast(CustomCameraPreview.this,
getString(R.string.picture_not_taken));
}
mCamera.release();
mButtonCapture.setEnabled(false);
}
};
protected void onCreate(){
initiCameraForVideo();
}
private void initiCameraForVideo() {
params = mCamera.getParameters();
mButtonCapture.setBackgroundResource(R.drawable.videostart);
mShowCamera = new CameraSurfaceHolder(CustomCameraPreview.this,
mCamera);
mLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
mLayout.removeAllViews();
mLayout.addView(mShowCamera);
List<Camera.Size> mSizeList_Video = null;// params.getSupportedPreviewSizes();
if (params.getSupportedVideoSizes() != null) {
mSizeList_Video = params.getSupportedVideoSizes();
} else {
// Video sizes may be null, which indicates that all the
// supported preview sizes are supported for video
// recording.
mSizeList_Video = mCamera.getParameters()
.getSupportedPreviewSizes();
}
}
#Override
public void onClick(View v) {
int viewId = v.getId();
switch (viewId) {
case R.id.button_Capture:
releaseCamera();
if (!prepareMediaRecorder()) {
Message.displayToast(
CustomCameraPreview.this,
getString(R.string.somethign_went_wrong));
} else {
mediaRecorder.start();
recording = true;
}
}
private boolean prepareMediaRecorder() \*method to setup media player to record video
{
mCamera = isCameraAvailable();
mediaRecorder = new MediaRecorder();
mCamera.unlock();
mediaRecorder.setCamera(mCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
if(CamcorderProfile.hasProfile(findCameraID(), CamcorderProfile.QUALITY_480P)) {
mediaRecorder.setProfile(CamcorderProfile
.get(CamcorderProfile.QUALITY_480P));
}else{
mediaRecorder.setProfile(CamcorderProfile
.get(CamcorderProfile.QUALITY_LOW));
}
mediaRecorder.setOutputFile(getOutputVideoFile());
mediaRecorder.setMaxDuration(60000);
// mediaRecorder.setMaxFileSize(100 * 1000 * 1000);
mediaRecorder.setPreviewDisplay(mShowCamera.getHolder().getSurface());
try {
mediaRecorder.prepare();
}
}
#Override
protected void onPause() {
super.onPause();
releaseMediaRecorder();
releaseCamera();
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
and this surface preview class-
public class CameraSurfaceHolder extends SurfaceView implements
SurfaceHolder.Callback {
private static final String TAG = "CameraSurfaceHolder";
Context mContext;
private String errorMessage = "";
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
public CameraSurfaceHolder(Context context, Camera camera) {
super(context);
mContext = context;
mCamera = camera;
mSurfaceHolder = getHolder();
mSurfaceHolder.addCallback(this);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
/*if (holder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
setCameraDisplayOrientation((Activity)mContext, Camera.CameraInfo.CAMERA_FACING_BACK, mCamera);
// start preview with new settings
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}
*/
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(mSurfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
Logger.ex(e);
}
}
public void setCameraDisplayOrientation(Activity activity, int cameraId,
Camera camera) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
/*Display mDisplay = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = mDisplay.getDisplayId();*/
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
Camera.Parameters mParameters = camera.getParameters();
mParameters.setRotation(rotation);
camera.setDisplayOrientation(result);
camera.setParameters(mParameters);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
in above class I added some code like below and when user touch on camera preview its throwing null pointer exception in onTouchEvent() on access of camera paramters. Also tried like I set again camera object to surface in activity after configure media recorder(prepareMediaRecorder()), but zoom function working but video is not recording.
#Override
public boolean onTouchEvent(MotionEvent event) {
// Get the pointer ID
Camera.Parameters params = mCamera.getParameters();
int action = event.getAction();
if (event.getPointerCount() > 1) {
// handle multi-touch events
if (action == MotionEvent.ACTION_POINTER_DOWN) {
mDist = getFingerSpacing(event);
} else if (action == MotionEvent.ACTION_MOVE && params.isZoomSupported()) {
mCamera.cancelAutoFocus();
handleZoom(event, params);
}
} else {
// handle single touch events
if (action == MotionEvent.ACTION_UP) {
handleFocus(event, params);
}
}
return true;
}
private void handleZoom(MotionEvent event, Camera.Parameters params) {
int maxZoom = params.getMaxZoom();
int zoom = params.getZoom();
float newDist = getFingerSpacing(event);
if (newDist > mDist) {
//zoom in
if (zoom < maxZoom)
zoom++;
} else if (newDist < mDist) {
//zoom out
if (zoom > 0)
zoom--;
}
mDist = newDist;
params.setZoom(zoom);
mCamera.setParameters(params);
}
public void handleFocus(MotionEvent event, Camera.Parameters params) {
int pointerId = event.getPointerId(0);
int pointerIndex = event.findPointerIndex(pointerId);
// Get the pointer's current position
float x = event.getX(pointerIndex);
float y = event.getY(pointerIndex);
List<String> supportedFocusModes = params.getSupportedFocusModes();
if (supportedFocusModes != null && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
mCamera.autoFocus(new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(boolean b, Camera camera) {
// currently set to auto-focus on single touch
}
});
}
}
/** Determine the space between the first two fingers */
private float getFingerSpacing(MotionEvent event) {
// ...
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float)Math.sqrt(x * x + y * y);
}
I'm working on a android project, where there is an overlay button that is on top of other apps as well and when this button is clicked a screenshot should be taken. The overlay button works, but the screenshot part doesn't. I don't know why but it seems that the OnImageAvailable isn't starting. Here is a seperate project where I only test the screenshot part:
public class MainActivity extends Activity {
private static final int REQUEST_CODE= 100;
private MediaProjectionManager mProjectionManager;
private MediaProjection mProjection;
private ImageReader mImageReader;
private Handler mHandler = new Handler(Looper.getMainLooper());
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// call for the projection manager
mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
imageView = (ImageView) findViewById(R.id.imageView);
// start projection
final Button startButton = (Button)findViewById(R.id.button);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startProjection();
}
});
// start capture handling thread
new Thread() {
#Override
public void run() {
Looper.prepare();
mHandler = new Handler();
Looper.loop();
}
}.start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
mProjection = mProjectionManager.getMediaProjection(resultCode, data);
if (mProjection != null) {
final DisplayMetrics metrics = getResources().getDisplayMetrics();
final int density = metrics.densityDpi;
final int flags = DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY | DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC;
final Display display = getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
final int width = size.x;
final int height = size.y;
mImageReader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 2);
mProjection.createVirtualDisplay("screencap", width, height, density, flags, mImageReader.getSurface(), null, mHandler);
mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
Bitmap bitmap = null;
try {
image = mImageReader.acquireLatestImage();
if (image != null) {
final Image.Plane[] planes = image.getPlanes();
int width = image.getWidth();
int height = image.getHeight();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * width;
byte[] newData = new byte[width*height*4];
int offset = 0;
bitmap = Bitmap.createBitmap(metrics, width, height, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = planes[0].getBuffer();
for(int i = 0; i < height; ++i){
for(int j = 0; j < width; ++j){
int pixel = 0;
pixel |= (buffer.get(offset) & 0xff) << 16; // R
pixel |= (buffer.get(offset + 1) & 0xff) << 8; // G
pixel |= (buffer.get(offset + 2) & 0xff); // B
pixel |= (buffer.get(offset + 3) & 0xff) << 24; // A
bitmap.setPixel(j, i, pixel);
offset += pixelStride;
}
offset += rowPadding;
}
imageView.setImageBitmap(bitmap);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bitmap!=null)
bitmap.recycle();
if (image!=null)
image.close();
}
}
}, mHandler);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startProjection() {
startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
}
}
I think you should set a different FLAGS.
You're telling the MediaProjection to display ITS OWN CONTENT ONLY but you're not drawing nothing on its surface.
To do a screenshot you have to REPLICATE A DIFFERENT DISPLAY using "DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR" flag.
First of all, I am picking an image from the gallery and converting it into bitmap.
What i want to achieve is that, when a certain button is pressed, a new bitmap is created with double the number of pixels in the previously stored bitmap. Next, each pixel from the original bitmap should be stored in four pixels around the same co ordinates in the new bitmap.
I have tried looping through both of the bitmaps but I'm getting an error which says Y SHOULD BE > BITMAP.HEIGHT()
not sure what I'm getting wrong here.
And even if i fix this error in the loop, can the UI thread even manage to loop through a large number of pixels without becoming unresponsive?
The MainActivity code is pasted below:
public class MainActivity extends AppCompatActivity {
static final int PICK_IMAGE = 11;
ImageView image;
Bitmap bmp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button chooseImage = (Button) findViewById(R.id.choose_btn);
Button apply = (Button) findViewById(R.id.apply_btn);
image = (ImageView) findViewById(R.id.image_view);
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
});
apply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int viewHeight = image.getHeight();
int viewWidth = image.getWidth();
int bmpHeight = bmp.getHeight();
int bmpWidth = bmp.getWidth();
Bitmap betterQuality = Bitmap.createBitmap(bmpWidth*2, bmpHeight*2, Bitmap.Config.ARGB_8888);
int newXVal = 0, newYVal = 0, limX = 2, limY = 2;
int color;
for (int x = 0; x < bmpWidth; x++) {
for (int y = 0; y < bmpHeight; y++) {
for (int a = newXVal; a < limX; a++) {
for (int b = newYVal; b < limY; b++) {
color = bmp.getPixel(x, y);
betterQuality.setPixel(a, b, Color.argb(Color.alpha(color), Color.red(color), Color.blue(color), Color.green(color)));
}
}
newXVal++;
newYVal++;
limX++;
limY++;
}
}
image.setImageBitmap(betterQuality);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK){
Uri selectedImage = data.getData();
try {
bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage));
image.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}