how to intergrate decode method to slideshow android - android

Im having problem integrating method for scaling images thru method on animate slide show. My goal is i have 10 large images that i will us for slide show, when i try to test 2 images its working perfectly, but when i try to use all the images it gives me error java.lang.OutOfMemoryError: bitmap size exceeds VM budget, i search on the internet, i came up to scale the images or use bitmap, several codes i got, but my problem is that how can i integrate the bitmap/decode codes that i got from the net to my slideshow script.
below is the script:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class SliderActivity extends Activity {
public int currentimageindex=0;
Timer timer;
TimerTask task;
ImageView slidingImage;
private int[] IMAGE_IDS = {
R.drawable.pic1edited, R.drawable.pic2edited, R.drawable.pic3edited,
R.drawable.pic4edited, R.drawable.pic5edited
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set fullscreen and no title
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main_slider);
Bitmap image = BitmapFactory.decodeResource(getResources(), getResources().getIdentifier( "imagename" , "drawable", getPackageName()));
final Handler mhandler = new Handler();
//Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
#Override
public void run() {
AnimateandSlideShow();
}
};
int delay = 1000; //delay for 1 sec
int period = 8000; //repeat every 4 sec
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
mhandler.post(mUpdateResults);
}
}, delay, period);
}
//Helper method to start the animation on the splash screen
private void AnimateandSlideShow() {
slidingImage = (ImageView)findViewById(R.id.imageView1);
slidingImage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.fade_in);
slidingImage.setAnimation(rotateimage);
Log.d(getClass().getName(), "value = " + currentimageindex);
}
private Drawable resize(Drawable image) {
Bitmap b = ((BitmapDrawable)image).getBitmap();
Bitmap bitmapResized = Bitmap.createScaledBitmap(b, 50, 50, false);
return new BitmapDrawable(bitmapResized);
}
private Bitmap decodeFile(File f){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_SIZE=70;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
//override some buttons
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Log.d("button", new Integer(keyCode).toString());
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
return false;
}
else if ((keyCode == KeyEvent.KEYCODE_CALL)) {
return false;
}
else if ((keyCode == KeyEvent.KEYCODE_MENU)) {
return false;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}

Related

changing image with imageswitcher and onTouch

I want to make android app like the following site.
https://sectional-anatomy.org/ct-abdomen/ or like https://radiopaedia.org/cases/squamous-cell-carcinoma-oral-cavity
There are multiple pictures and these are changing by scrolling.
I have done something like that with imageswitcher and onTouch event with action_down and action_up but it doesn't work because when I remove my finger then it goes to the first image it doesn't stay where I left.
Here is my code:
package com.radiology.radiologymenu.tomografi;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import com.radiology.radiologymenu.R;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class ImageChangeActivity extends AppCompatActivity {
private ImageSwitcher imageSwitcher;
private ImageView box;
// Size
private int frameHeight;
private int boxSize;
private int screenHeight;
// Position
private int boxY;
// Speed
private int boxSpeed;
// Score
private int score = 0;
// Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();
// Status Check
private boolean action_flg = false;
private boolean start_flg = false;
private String pic;
private ArrayList<Integer> slidePictures;
private static final Integer[] image= {
R.drawable.sagittal_boyun_1, R.drawable.sagittal_boyun_2, R.drawable.sagittal_boyun_3, R.drawable.sagittal_boyun_4,
R.drawable.sagittal_boyun_5, R.drawable.sagittal_boyun_6, R.drawable.sagittal_boyun_7, R.drawable.sagittal_boyun_8,
R.drawable.sagittal_boyun_9, R.drawable.sagittal_boyun_10, R.drawable.sagittal_boyun_11,
R.drawable.sagittal_boyun_12, R.drawable.sagittal_boyun_13, R.drawable.sagittal_boyun_14, R.drawable.sagittal_boyun_15,
R.drawable.sagittal_boyun_16, R.drawable.sagittal_boyun_17, R.drawable.sagittal_boyun_18, R.drawable.sagittal_boyun_19,
R.drawable.sagittal_boyun_20, R.drawable.sagittal_boyun_21, R.drawable.sagittal_boyun_22, R.drawable.sagittal_boyun_23,
R.drawable.sagittal_boyun_24, R.drawable.sagittal_boyun_25, R.drawable.sagittal_boyun_26, R.drawable.sagittal_boyun_27,
R.drawable.sagittal_boyun_28, R.drawable.sagittal_boyun_29, R.drawable.sagittal_boyun_30, R.drawable.sagittal_boyun_31,
R.drawable.sagittal_boyun_32, R.drawable.sagittal_boyun_33, R.drawable.sagittal_boyun_34, R.drawable.sagittal_boyun_35,
R.drawable.sagittal_boyun_36, R.drawable.sagittal_boyun_37, R.drawable.sagittal_boyun_38, R.drawable.sagittal_boyun_39,
R.drawable.sagittal_boyun_40, R.drawable.sagittal_boyun_41, R.drawable.sagittal_boyun_42, R.drawable.sagittal_boyun_43,
R.drawable.sagittal_boyun_44, R.drawable.sagittal_boyun_45 };
int i = 0;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_activity_main);
pic = getIntent().getExtras().getString("pic");
slidePictures = (ArrayList<Integer>) getIntent().getExtras().getSerializable("slidePictures");
getView2(pic,slidePictures);
}
public void getView2(String strings, ArrayList<Integer> slidePictures){
setContentView(R.layout.slide_activity_main);
TextView textView = (TextView) findViewById(R.id.resimText);
textView.setText(strings.toString());
imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
box = (ImageView) findViewById(R.id.box);
// Get screen size.
WindowManager wm = getWindowManager();
Display disp = wm.getDefaultDisplay();
Point size = new Point();
disp.getSize(size);
screenHeight = size.y;
boxSpeed = Math.round(screenHeight / 60); // 1280 / 60 = 21.333... => 21
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
#Override
public View makeView() {
ImageView imageView = new ImageView(getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
FrameLayout.LayoutParams params = new ImageSwitcher.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(params);
return imageView;
}
});
imageSwitcher.setImageResource(slidePictures.get(0));
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
finish();
}
return super.onKeyDown(keyCode, event);
}
public void changePos() {
// Move Box
if (action_flg == true) {
// Touching
boxY -= boxSpeed;
if (i<slidePictures.size()-1){
i++;
imageSwitcher.setImageResource(slidePictures.get(i));
}
} else {
// Releasing
boxY += boxSpeed;
if (i>0){
i--;
imageSwitcher.setImageResource(slidePictures.get(i));
}
}
// Check box position.
if (boxY < 0) boxY = 0;
if (boxY > frameHeight - boxSize) boxY = frameHeight - boxSize;
box.setY(boxY);
}
public boolean onTouchEvent(MotionEvent me) {
if (start_flg == false) {
start_flg = true;
// Why get frame height and box height here?
// Because the UI has not been set on the screen in OnCreate()!!
FrameLayout frame = (FrameLayout) findViewById(R.id.frame);
frameHeight = frame.getHeight();
boxY = (int)box.getY();
// The box is a square.(height and width are the same.)
boxSize = box.getHeight();
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
changePos();
}
});
}
}, 0, 40);
} else {
if (me.getAction() == MotionEvent.ACTION_DOWN) {
action_flg = false;
} else if (me.getAction() == MotionEvent.ACTION_UP) {
action_flg = true;
}
}
return true;
}
}

pick image from gallery error when setDrawable

I have a null pointer exception when i load an image in my imageview. I have searched in so many topic but i not found a solution. I don't know why this won't work :/ Ahm another small bug, before i made an Imageview parameter in the class i try to use something like ImageView profilPicture = (ImageView) findViewById(R.id.profil_picture); but this produce an "error" android studio tell me to create the method...
So there is the error code :
Caused by: java.lang.NullPointerException
at android.graphics.BitmapShader.<init>(BitmapShader.java:40)
at god.repertoire.RoundImage.<init>(RoundImage.java:30)
at god.repertoire.FragmentNoContact.onActivityResult(FragmentNoContact.java:83)
There is the code of my Fragment :
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class FragmentNoContact extends Fragment {
private static int RESULT_LOAD_IMG = 1;
ImageView profilPicture;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// GET FRAGMENT COMPONENT
View myView = inflater.inflate(R.layout.activity_no_contact, container, false);
FloatingActionButton addContact = (FloatingActionButton) myView.findViewById(R.id.button_add);
profilPicture = (ImageView) myView.findViewById(R.id.profil_picture);
// INIT PHOTO DE PROFIL
Bitmap img = SaveLoad.loadFromFile("profil_picture.jpg");
if (img == null)
img = BitmapFactory.decodeResource(getResources(), R.drawable.blank_profile);
RoundImage roundedImage = new RoundImage(img);
profilPicture.setImageDrawable(roundedImage);
// EVENT AU CLIC PHOTO
profilPicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
/* an example i used before to test if i can set an another image
ImageView profilPicture = (ImageView) v.findViewById(R.id.profil_picture);
Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.me);
RoundImage roundedImage = new RoundImage(img);
profilPicture.setImageDrawable(roundedImage);
*/
}
});
// ACTION BOUTON AJOUTER CONTACT
addContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
FragmentAddContact fragment2 = new FragmentAddContact();
transaction.add(R.id.myFrameLayout, fragment2);
transaction.addToBackStack("FragmentAddContact");
transaction.commit();
}
});
return myView;
}
// EVENT IMAGE SELECTED
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;//returning null for below statement
Bitmap img = BitmapFactory.decodeFile(selectedImage.toString(), options);
RoundImage roundedImage = new RoundImage(img);
profilPicture.setImageDrawable(roundedImage);
}
}
}
There is the code of the RoundImage class (it's a class to generate a crop circle image in an imageView) :
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
public class RoundImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;
public RoundImage(Bitmap bitmap) {
mBitmap = bitmap;
mRectF = new RectF();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
canvas.drawOval(mRectF, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
#Override
public void setAlpha(int alpha) {
if (mPaint.getAlpha() != alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
#Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
public void setAntiAlias(boolean aa) {
mPaint.setAntiAlias(aa);
invalidateSelf();
}
#Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
#Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
public Bitmap getBitmap() {
return mBitmap;
}
}
And finaly, there is the code xml to create the imageview :
<ImageView
android:id="#+id/profil_picture"
android:layout_width="128dp"
android:layout_height="128dp"
android:scaleType="centerCrop"/>
Try this it may help you.
int id3 = getResources().getIdentifier("com.example.admin:mipmap/status" , null, null);
((ImageView) findViewById(R.id.imageviewstatus)).setImageResource(id3);

Images not showing Properly in the ImageView

I am having a little problem with my android project I hope I will find a fix from you guys.
I am getting an image from Phone gallery or take the pic from the front or rare camera and setting it in an ImageView. Everything is working fine that I can get the image from the gallery and can take the pic from the camera and set it in the image view.
Problem:
The problem I am facing is that the orientation of the image is not what I want. When I Capture a picture from Front camera of my mobile the image is shown Right to left not from top to Bottom. Please see the following image:
And when I capture an image in Portrait (from rare camera) it is shown as Left to right in the ImageView not from Top to bottom.
And when I capture the image in Landscape mode it is shown normal in the ImageView i-e From Top to Bottom.
this is the landscape mode image output..
I don't know how I fix it.. so what i am missing or what i should do to make all the images in the ImageView in Top to Bottom view.
Here are my XML and Java Files:
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imgProfilePic"
android:layout_above="#+id/btnGetPic"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnGetPic"
android:layout_alignParentBottom="true"
android:text="Get pictures from Gallery or Camera"/>
</RelativeLayout>
Java File :
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
Button btnGetPic;
ImageView imgProfilePic;
private static int REQUEST_GALLERY = 1;
private static int REQUEST_CAMERA = 2;
RoundTheImage roundedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnGetPic = (Button) findViewById(R.id.btnGetPic);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
btnGetPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
Bundle bundle = new Bundle();
bundle = data.getExtras();
Bitmap bmp;
bmp = (Bitmap) bundle.get("data");
Bitmap resized = Bitmap.createScaledBitmap(bmp, 1000, 1000, true);
roundedImage = new RoundTheImage(resized);
imgProfilePic.setImageDrawable(roundedImage);
} else if (requestCode == REQUEST_GALLERY && null != data) {
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
Bitmap bmp;
bmp = BitmapFactory.decodeStream(inputStream);
Bitmap resized = Bitmap.createScaledBitmap(bmp, 1000, 1000, true);
roundedImage = new RoundTheImage(resized);
imgProfilePic.setImageDrawable(roundedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo from Camera", "Choose from Library", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo from Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent,REQUEST_CAMERA); // 1 as REQUEST_CAMERA
}
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), REQUEST_GALLERY);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
}
And I use this Class to round the edges of the images (I get this one from one of SO answers)
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
public class RoundTheImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;
public RoundTheImage(Bitmap bitmap) {
mBitmap = bitmap;
mRectF = new RectF();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
canvas.drawOval(mRectF, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
#Override
public void setAlpha(int alpha) {
if (mPaint.getAlpha() != alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
#Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
public void setAntiAlias(boolean aa) {
mPaint.setAntiAlias(aa);
invalidateSelf();
}
#Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
#Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
public Bitmap getBitmap() {
return mBitmap;
}
}
How to set Android camera orientation properly?
Have a look at that, it should answer your question. Essentially you need to tell the app what orientation the camera is in based on the phone sensor and that should allow you to capture in the correct orientation. Hope it helps!
Thanks to hipkiss for pointing me toward right direction.
Please note: This is not the best solution out there and it may not be well optimised and it may not work with every device.
For newcomers, like me, here is what my final code looked like. So it may help someone some day :)
First do this in your button's click event or in alert dialog etc
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, REQUEST_GALLERY);
declare
REQUEST_GALLERY as
private static int REQUEST_GALLERY = 1;
And now in your
onActivityResult Do something like this:
try {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
int rotation = getCameraPhotoOrientation(MainActivity.this,selectedImage,imgPath);
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
Bitmap original = BitmapFactory.decodeFile(imgPath);
Bitmap myFinalImg = Bitmap.createBitmap(original, 0, 0, original.getWidth(), original.getHeight(), matrix, true);
ImageView imgView = (ImageView) findViewById(R.id.imgProfilePic);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(myFinalImg);
} catch (Exception e) {
Toast.makeText(this, "Unable to load the image", Toast.LENGTH_LONG).show();
}
And this function will return the rotation ( that is how much rotation should be done)
public static int getCameraPhotoOrientation(Context context, Uri imageUri, String imagePath) {
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageUri, null);
File imageFile = new File(imagePath);
ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
rotate = 0;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
#Pros out there please fix/improve this answer so it may help other and let me know how i can improve it too :)
Edit:
Don't forget to add the permission in AndroidManifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Android images gridview

The code to display the images from sd card and whatsapp in the app but when I run the code the pictures are displayed but there are random whitespaces between photos and the photos are not of the same size. How do I resize the image ? Heres the code for the main activity:
import java.io.File;
import java.util.ArrayList;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ImageAdapter imageAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
imageAdapter = new ImageAdapter(this);
gridview.setAdapter(imageAdapter);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/DCIM/Camera";
File f=new File(Environment.getExternalStorageDirectory()+"/WhatsApp");
if(f.exists()){
String path=Environment.getExternalStorageDirectory()+"/WhatsApp/Media/WhatsApp Images";
File t=new File(path);
File[] fo=t.listFiles();
for(File fil : fo){
imageAdapter.add(fil.getAbsolutePath());
}
}
Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
imageAdapter.add(file.getAbsolutePath());
}
}
Heres the code for image adapter:
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context context;
ArrayList<String> imageList = new ArrayList<String>();
public ImageAdapter(Context c) {
context = c;
}
void add(String path){
imageList.add(path);
}
#Override
public int getCount() {
return imageList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(100,100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = decodeSampledBitmapFromUri(imageList.get(position), 100,100);
imageView.setImageBitmap(bm);
return imageView;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
Bitmap bm = null;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
As I said before, the code runs but the sizee of the image is not uniform and there are whitespaces. Please help me solve it.
try to set the scale type fit_xy
imageView.setScaleType(ImageView.ScaleType.FIT_XY);

AnimationDrawable into framelayout beside SurfaceView- Android

Hello all,
in my app, can i make an character (like, cartoon character...) to animate when i touch the screen?
i have another bitmaps (static not animated) on the screen.
i have all this character (10) bitmaps in all animation position (like a cartoon)
this is the code.. ( I NEED TO ANIMATE IT FOR EACH TOUCH )
`
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
public class Show extends Activity
{
private Bitmap imageOne;
private Bitmap imageTwo;
private Bitmap imageThree;
private List<Bitmap> images;
private ExplainView myView;
private AnimationDrawable animation;
private ImageView image;`
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(0x00000400, 0x00000400);
setContentView(R.layout.frame_layout);
image = new ImageView(this);
image.setBackgroundResource(R.drawable.tom_anim);
animation = (AnimationDrawable) rocketImage.getBackground();
images = new ArrayList<Bitmap>();
praper();
myView = new ExplainView(this,images,1); <------ this is the surface view class
FrameLayout fl = (FrameLayout)findViewById(R.id.frameLayout);
fl.addView(myView);
fl.addView(image);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
new Runnable() {
#Override
public void run() {
image.setVisibility(View.VISIBLE);
animation.stop();
animation.start();
}
};
}
return true;
}
private void praper()
{
imageOne = BitmapFactory.decodeResource(getResources(), R.drawable.trans_ar_alpha_1);
imageTwo = BitmapFactory.decodeResource(getResources(), R.drawable.trans_ar_alpha_2);
imageThree = BitmapFactory.decodeResource(getResources(), R.drawable.trans_ar_alpha_3);
images.add(0,imageOne);
images.add(1, imageTwo);
images.add(2, imageThree);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
if(hasFocus)
{
animation.start();
}
else
{
animation.stop();
}
}
}`
of course you can simply by using
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
x = arg1.getX();
y = arg1.getY();
switch(arg1.getAction())
{
case MotionEvent.ACTION_DOWN:
sx=arg1.getX();
sy = arg1.getY();
break;
case MotionEvent.ACTION_UP:
fx=arg1.getX();
fy = arg1.getY();
break;
}

Categories

Resources