how to change the image size - java

In this piece of my code i want to change the image when i click on it. How i can do this?
I use img.setOnClickListenser but really i don't know what the code must put in it
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gallery_img2, container, false);
Log.d("start_new_frg gallery_img ", "ok");
back = (Button)rootView.findViewById(R.id.button1);
if (id == -1 ){
Toast.makeText(getActivity(), "bad Entry ", Toast.LENGTH_LONG).show();
onBackPressed();
getActivity().finish();
}
imgv = (ImageView) rootView.findViewById(R.id.imageView1);
String ROOT = Environment.getExternalStorageDirectory().getPath()+"/POSTSIMAGES/";
final Bitmap image = BitmapFactory.decodeFile(ROOT+String.valueOf(g.getId())+"q.jpg");
File f = new File(ROOT+String.valueOf(g.getId())+"q.jpg");
temp=ROOT;
if(!f.exists()){
imgv.setImageResource(R.drawable.logo_and);
}
else
{
imgv.setImageBitmap(image);
}
if( isNetworkConnected( )){
new conn().execute("");
}else{
// pd.dismiss();
// if(ROOT.endsWith("_s"))
// {
//
//
// }
imgv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// your code here
Log.d("inside onclick", "ok");
String _n=temp.replace("_s.jpg", "_n.jpg");
imageLoader2.DisplayImage(_n,imgv );
// imgv.setScaleType(ImageView.ScaleType.FIT_XY);
}
});
}
//////////////////////// ADS ///////////////////////
// Create the adView
adView = new AdView(getActivity(), AdSize.SMART_BANNER, "a150f45ea765784");
// Lookup your LinearLayout assuming it's been given
// the attribute android:id="#+id/mainLayout"
LinearLayout layout = (LinearLayout)rootView.findViewById(R.id.ADS);
// Add the adView to it
layout.addView(adView);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
//////////////////////// END ADS ///////////////////////
back.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Fragment newFragment = new Gallery(getActivity());
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(android.R.id.content, newFragment);
// transaction.addToBackStack(null);
// Commit the transaction
// transaction.remove(mFragment);
transaction.commit();
}
});
return rootView;
}

Use same code to create another bitmap of the image you want and assign it to your Imageview.
imgv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// your code here
final Bitmap new_image = BitmapFactory.decodeFile(ROOT+String.valueOf(g.getId())+"q.jpg");
imgv.setImageBitmap(new_image);
}
});

Try this one
final Bitmap image = BitmapFactory.decodeFile(ROOT+String.valueOf(g.getId())+"q.jpg");
Bitmap bitmapimage = Bitmap.createScaledBitmap(image, 60, 60, true);
or you can call this method pass path of the image and size of width and height like 60 and 60
public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
return bmp;
}
public static 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;
}

Related

when trying to make circle bitmap the background remains square

so i am trying now for about a week to get this thing working but to no avail....
i want the user to pick an image from his gallery and then crop that image into a nice circle profile photo i get the photo to crop but the background is still square.... i found this question and tried implementing the answer he gave but still the background is square Cropping circular area from bitmap in Android
i googled and just found more ways to do it but still gets the square background.... any help will be appreciated
public class RegisterActivity extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
RoundedImageView roundImageView ;
String numberToPass = "1";//default 1 for male
String selectedImagePath;
EditText etNickname, etAge;
Button btnNext;
ImageView profilePhoto, imageview;
Bitmap bitmap;
private OnRegisterListener mListener;
public RegisterActivity() {
// Required empty public constructor
}
public static RegisterActivity newInstance(String param1, String param2) {
RegisterActivity fragment = new RegisterActivity();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_register, container, false);
etNickname = (EditText) view.findViewById(R.id.etNickName);
btnNext = (Button) view.findViewById(R.id.btnNextRegister);
profilePhoto = (ImageView) view.findViewById(R.id.imageButton);
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.blender);
// profilePhoto.setImageBitmap(bitmap);
/* Bitmap bitmap2 = BitmapFactory.decodeResource(this.getResources(),R.drawable.blender);
Bitmap circularBitmap = ImageConverter.getRoundedCornerBitmap(bitmap2, 100);
ImageView circularImageView = (ImageView)view.findViewById(R.id.imageButton);
circularImageView.setImageBitmap(circularBitmap); */
profilePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnRegisterListener) {
mListener = (OnRegisterListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnRegisterListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnRegisterListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
//this allows the uset to select one image from openGallery
public void openGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, 1);
}
//when starting activity for result and choose an image, the code will automatically continue here
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 1 && null != data) {
if (requestCode == 1) {
Uri current_ImageURI = data.getData();
/* String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(current_ImageURI,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();*/
selectedImagePath = getPath(current_ImageURI);
profilePhoto.setImageBitmap(circleBitmap(decodeSampledBitmap(new File(selectedImagePath), 250, 250)));
}
}
}
public String getPath(Uri contentUri) {
// we have to check for sdk version because from lollipop the retrieval of path is different
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// can post image
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getApplicationContext().getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else {
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
}
public Bitmap decodeSampledBitmap(File res, int reqWidth, int reqHeight) {
if (res != null) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
FileInputStream stream2 = null;
try {
stream2 = new FileInputStream(res);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BitmapFactory.decodeStream(stream2, null, options);
stream2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Calculate inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
o2.inJustDecodeBounds = false;
FileInputStream stream = null;
try {
stream = new FileInputStream(res);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(stream, null, o2);
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
} else
return null;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
//-----------------------------------------------------------------
private Bitmap circleBitmap(Bitmap bitmap) {
final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
int squareBitmapWidth = Math.min(bitmap.getWidth(), bitmap.getHeight());
/* Canvas
The Canvas class holds the "draw" calls. To draw something, you need 4 basic
components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing
into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), and a paint
(to describe the colors and styles for the drawing). */
final Canvas canvas = new Canvas(output);
final int color = Color.RED;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
// final Rect rect = new Rect(0, 0, squareBitmapWidth, squareBitmapWidth);
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint);
//canvas.drawOval(rectF, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
//float left = (squareBitmapWidth - bitmap.getWidth()) / 2;
//float top = (squareBitmapWidth - bitmap.getHeight()) / 2;
//canvas.drawBitmap(bitmap, left, top, paint);
canvas.drawBitmap(bitmap, rect, rect, paint);
//bitmap.recycle();
return output;
}
//---------------------------------------------------------------------------------------------
//end img upload
I use this code and it works perfectly:
public static Bitmap getCircularBitmap(Bitmap bitmap) {
Bitmap output;
if (bitmap.getWidth() > bitmap.getHeight()) {
output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
} else {
output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
float r = 0;
if (bitmap.getWidth() > bitmap.getHeight()) {
r = bitmap.getHeight() / 2;
} else {
r = bitmap.getWidth() / 2;
}
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(r, r, r, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
You can custom ImageView to make its all drawing things circular. Here is my implementation(not the best solution for performance-eager application but good enough for condition that don't invalidate ImageView much):
class CircleImageView extends ImageView {
private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public CircleImageView(Context context) {
super(context);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int radiusMeasureSpec = widthMeasureSpec;
super.onMeasure(radiusMeasureSpec, radiusMeasureSpec);
int radiusMeasureSize = MeasureSpec.getSize(widthMeasureSpec);
setMeasuredDimension(radiusMeasureSize, radiusMeasureSize);
}
#Override
public void draw(Canvas viewCanvas) {
final int EDGE_SIZE = viewCanvas.getWidth();
// Draw this View's things.
Bitmap fgBm = Bitmap.createBitmap(EDGE_SIZE, EDGE_SIZE, Bitmap.Config.ARGB_8888);
Canvas fgCanvas = new Canvas(fgBm);
super.draw(fgCanvas);
// Transfer to a special shape.
Bitmap shapedBm = Bitmap.createBitmap(EDGE_SIZE, EDGE_SIZE, Bitmap.Config.ARGB_8888);
Canvas shapedCanvas = new Canvas(shapedBm);
shapedCanvas.drawCircle(EDGE_SIZE/2, EDGE_SIZE/2, EDGE_SIZE/2, mPaint);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
shapedCanvas.drawBitmap(fgBm, 0, 0, mPaint);
mPaint.setXfermode(null);
// Move drawn things to View's canvas.
viewCanvas.drawBitmap(shapedBm, 0, 0, mPaint);
fgBm.recycle();
shapedBm.recycle();
}
}
There's someone who customizes ImageView using BitmapShader in an SO post without Xfermode and create extra Bitmap instances. Here's his implementation.
you can use trusted library like This one
Adding circle image adding border to your image and some other feature

how can I get path list folder Android and set in Int Array.

I'm new in Android sorry....
I save any pictures in my App not SDCARD.
I use this code for get path but this code return String Array, I need return Int Array for my class CustomSwipeAdpter, this class for Page View.
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to data/data/yourapp/app_data/imageDir
new_folder = cw.getDir(pasta, Context.MODE_PRIVATE);
ArrayList<String> arquivos = new ArrayList<String> ();
if (!new_folder.exists()){
new_folder.mkdir();
}
// verifica a pasta se tem arquivo //
File[] files = new_folder.listFiles();
if ((files.length > 0)) {
String[] fileArray = new String[files.length];
int[] fileArrayInt = new int[files.length];
for (int i = 0; i < files.length; ++i) {
fileArray[i] = files[i].getAbsolutePath();
}
//filesResource[i] = Integer.parseInt(files[i].getAbsolutePath());
}
I will get this paths in this Class In Page View, this class is work with R.drawable.image01, i need change for my paths...
public class CustomSwipeAdpter extends PagerAdapter {
private int[] image_resources = {R.drawable.image01, R.drawable.image02, R.drawable.image03,
R.drawable.image04, R.drawable.image05, R.drawable.image06, R.drawable.image07, R.drawable.image08};
private Context ctx;
private LayoutInflater layoutInflater;
private Resources resource;
public CustomSwipeAdpter(Context ctx) {
this.ctx = ctx;
resource = ctx.getResources();
}
#Override
public int getCount() {
return image_resources.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.swipe_layout, container, false);
ImageView imageView = (ImageView) item_view.findViewById(R.id.imageView);
imageView.setImageBitmap(
decodeSampledBitmapFromResource(resource,
image_resources[position],
1080,
2560));
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 2;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
This class is fine when i use:
private int[] image_resources = {R.drawable.image01, R.drawable.image02, R.drawable.image03,
R.drawable.image04, R.drawable.image05, R.drawable.image06, R.drawable.image07, R.drawable.image08};
I need set this image_resources the my path.
May you could try follow way instead of resources:
Bitmap bitmap = BitmapFactory.decodeFile(fileArray[position]);

Why won't my undo button work in android java?

I have an image which a user can paint on in my android application. I decided to add an undo button to it so the user can cancel mistakes. I made it so that when the user draws on the screen, it saves the bitmap to an array. Then when the undo button is pressed, it changes the image to the last bitmap in the array. However, this just keeps setting the image to whatever the current image is (i.e. it doesn't change it at all).
public class edit extends AppCompatActivity implements View.OnClickListener {
float MoveX,MoveY,DownY,DownX,UpY=0,UpX ;
List<Bitmap> undos = new ArrayList<Bitmap>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
final ImageButton btn2 = (ImageButton) findViewById(R.id.imageButton2);
btn2.setOnClickListener(this);
final Button buttonchoose = (Button) findViewById(R.id.buttonchoose);
buttonchoose.setOnClickListener(this);
final RelativeLayout ViewX = (RelativeLayout) findViewById(R.id.RLXV);
ViewTreeObserver vto = ViewX.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewX.getViewTreeObserver().removeOnGlobalLayoutListener(this);
Intent intent7 = getIntent();
String bitmapXY = (String) intent7.getExtras().get("BitmapImage");
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/" + bitmapXY,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
HttpURLConnection connection = null;
try {
int ViewWidth = ViewX.getMeasuredWidth();
JSONObject photos = response.getJSONObject();
JSONArray linkY = photos.optJSONArray("images");
final JSONObject linkO = linkY.optJSONObject(0);
final String link2 = linkO.optString("source");
URL LINKF = new URL(link2);
connection = (HttpURLConnection) LINKF.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
float HH = (float) bitmap.getHeight();
float WW = (float) bitmap.getWidth();
float ViewWidthX = (float) ViewWidth;
float height = (HH / WW) * ViewWidthX;
Bitmap bitmapF = Bitmap.createScaledBitmap(bitmap, ViewWidth, Math.round(height), false);
final ImageView image1 = (ImageView) findViewById(R.id.image1);
image1.setImageBitmap(bitmapF);
undos.add(bitmapF);
image1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Display d = getWindowManager().getDefaultDisplay();
float dw = d.getWidth();
float dh = d.getHeight();
float x = event.getX();
float y = event.getY();
float r = 2;
Bitmap BTX = ((BitmapDrawable)image1.getDrawable()).getBitmap();
Canvas canvas = new Canvas(BTX);
canvas.drawBitmap(BTX,0,0,null);
Paint paint1 = new Paint();
int bg1 = buttonchoose.getDrawingCacheBackgroundColor();
ColorDrawable buttonColor = (ColorDrawable) buttonchoose.getBackground();
int bg2 =buttonColor.getColor();
paint1.setColor(bg2);
paint1.setShadowLayer(5, 2, 2, bg2);
paint1.setStrokeWidth(20);
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
DownY = event.getY();
DownX = event.getX();
break;
case MotionEvent.ACTION_MOVE:
MoveY = event.getY();
MoveX = event.getX();
canvas.drawLine(DownX, DownY, MoveX, MoveY, paint1);
image1.invalidate();
DownX = MoveX;
DownY=MoveY;
break;
case MotionEvent.ACTION_UP:
UpY = event.getY();
UpX = event.getX();
canvas.drawLine(DownX, DownY, UpX, UpY, paint1);
image1.invalidate();
Bitmap BTXYZ = ((BitmapDrawable)image1.getDrawable()).getBitmap();
break;
}
return true;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "images");
request.setParameters(parameters);
request.executeAsync();
}
});
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.buttonchoose:
final ColorPicker cp = new ColorPicker(edit.this, 0, 0, 0);
/* Show color picker dialog */
cp.show();
/* On Click listener for the dialog, when the user select the color */
Button okColor = (Button) cp.findViewById(R.id.okColorButton);
okColor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* You can get single channel (value 0-255) */
int selectedColorR = cp.getRed();
int selectedColorG = cp.getGreen();
int selectedColorB = cp.getBlue();
/* Or the android RGB Color (see the android Color class reference) */
int selectedColorRGB = cp.getColor();
Button buttonchoose = (Button) findViewById(R.id.buttonchoose);
buttonchoose.setText("");
buttonchoose.setBackgroundColor(selectedColorRGB);
cp.dismiss();
}
});
break;
case R.id.imageButton2:
int newImage = undos.size();
Log.e("Lenght of Array",""+newImage);
if(newImage >=1) {
Bitmap newImage2 = undos.get(newImage-2);
ImageView IMGXV = (ImageView) findViewById(R.id.image1);
IMGXV.setImageBitmap(newImage2);
undos.remove(newImage-1);
}
break;
}
}
}
Try this exact code -
case R.id.imageButton2:
if(undos.size() > 0) {
Bitmap newImage2 = undos.remove(undos.size() - 1);
ImageView IMGXV = (ImageView) findViewById(R.id.image1);
IMGXV.setImageBitmap(newImage2);
}
break;
EDIT Added an extra line in onGlobalLayout(), try this -
Bitmap bitmapF = Bitmap.createScaledBitmap(bitmap, ViewWidth, Math.round(height), false);
final ImageView image1 = (ImageView) findViewById(R.id.image1);
image1.setImageBitmap(bitmapF);
//The extra line before adding bitmap to arraylist.
Bitmap bitmapFcopy = bitmapFcopy.copy(bitmapFcopy.getConfig(), true);
undos.add(bitmapFcopy);
EDIT 2
public class edit extends AppCompatActivity implements View.OnClickListener {
//Declare the imageview here and access this everywhere.
ImageView image1;
float MoveX,MoveY,DownY,DownX,UpY=0,UpX ;
List<Bitmap> undos = new ArrayList<Bitmap>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
//Get the reference here
image1 = (ImageView) findViewById(R.id.image1);
final ImageButton btn2 = (ImageButton) findViewById(R.id.imageButton2);
btn2.setOnClickListener(this);
final Button buttonchoose = (Button) findViewById(R.id.buttonchoose);
buttonchoose.setOnClickListener(this);
final RelativeLayout ViewX = (RelativeLayout) findViewById(R.id.RLXV);
ViewTreeObserver vto = ViewX.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewX.getViewTreeObserver().removeOnGlobalLayoutListener(this);
Intent intent7 = getIntent();
String bitmapXY = (String) intent7.getExtras().get("BitmapImage");
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/" + bitmapXY,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
HttpURLConnection connection = null;
try {
int ViewWidth = ViewX.getMeasuredWidth();
JSONObject photos = response.getJSONObject();
JSONArray linkY = photos.optJSONArray("images");
final JSONObject linkO = linkY.optJSONObject(0);
final String link2 = linkO.optString("source");
URL LINKF = new URL(link2);
connection = (HttpURLConnection) LINKF.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
float HH = (float) bitmap.getHeight();
float WW = (float) bitmap.getWidth();
float ViewWidthX = (float) ViewWidth;
float height = (HH / WW) * ViewWidthX;
Bitmap bitmapF = Bitmap.createScaledBitmap(bitmap, ViewWidth, Math.round(height), false);
//Remove from here and declare this in onCreate() and don't make it final
//final ImageView image1 = (ImageView) findViewById(R.id.image1);
image1.setImageBitmap(bitmapF);
undos.add(bitmapF);
image1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Display d = getWindowManager().getDefaultDisplay();
float dw = d.getWidth();
float dh = d.getHeight();
float x = event.getX();
float y = event.getY();
float r = 2;
Bitmap BTX = ((BitmapDrawable)image1.getDrawable()).getBitmap();
Canvas canvas = new Canvas(BTX);
canvas.drawBitmap(BTX,0,0,null);
Paint paint1 = new Paint();
int bg1 = buttonchoose.getDrawingCacheBackgroundColor();
ColorDrawable buttonColor = (ColorDrawable) buttonchoose.getBackground();
int bg2 =buttonColor.getColor();
paint1.setColor(bg2);
paint1.setShadowLayer(5, 2, 2, bg2);
paint1.setStrokeWidth(20);
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
DownY = event.getY();
DownX = event.getX();
break;
case MotionEvent.ACTION_MOVE:
MoveY = event.getY();
MoveX = event.getX();
canvas.drawLine(DownX, DownY, MoveX, MoveY, paint1);
image1.invalidate();
DownX = MoveX;
DownY=MoveY;
break;
case MotionEvent.ACTION_UP:
UpY = event.getY();
UpX = event.getX();
canvas.drawLine(DownX, DownY, UpX, UpY, paint1);
image1.invalidate();
Bitmap BTXYZ = ((BitmapDrawable)image1.getDrawable()).getBitmap();
break;
}
return true;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "images");
request.setParameters(parameters);
request.executeAsync();
}
});
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.buttonchoose:
final ColorPicker cp = new ColorPicker(edit.this, 0, 0, 0);
/* Show color picker dialog */
cp.show();
/* On Click listener for the dialog, when the user select the color */
Button okColor = (Button) cp.findViewById(R.id.okColorButton);
okColor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* You can get single channel (value 0-255) */
int selectedColorR = cp.getRed();
int selectedColorG = cp.getGreen();
int selectedColorB = cp.getBlue();
/* Or the android RGB Color (see the android Color class reference) */
int selectedColorRGB = cp.getColor();
Button buttonchoose = (Button) findViewById(R.id.buttonchoose);
buttonchoose.setText("");
buttonchoose.setBackgroundColor(selectedColorRGB);
cp.dismiss();
}
});
break;
case R.id.imageButton2:
int newImage = undos.size();
Log.e("Lenght of Array",""+newImage);
if(newImage >=1) {
Bitmap newImage2 = undos.get(newImage-2);
//Don't take reference again here
//ImageView IMGXV = (ImageView) findViewById(R.id.image1);
image1.setImageBitmap(newImage2);
undos.remove(newImage-1);
}
break;
}
}
}

How can i set alignment of horizontalScrollView of images

I have created list of images in horizontal fashion using horizontalscrollview its working fine but i want to show last image always because its capturing image.
My Layout
<HorizontalScrollView
android:id="#+id/horizontal_scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.activities.MyHorizontalLayout
android:id="#+id/linear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
/>
</HorizontalScrollView>
HorizontalScrollView Class
public class MyHorizontalLayout extends LinearLayout {
Context myContext;
ArrayList<String> itemList = new ArrayList<String>();
public Bitmap selectedbm;
public static String selectedfile;
public MyHorizontalLayout(Context context) {
super(context);
myContext = context;
}
public MyHorizontalLayout(Context context, AttributeSet attrs) {
super(context, attrs);
myContext = context;
}
public MyHorizontalLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
myContext = context;
}
void add(String path) {
int newIdx = itemList.size();
itemList.add(path);
addView(getImageView(newIdx));
}
void remove(String path,int ind) {
removeView(getImageView(ind));
itemList.remove(ind);
}
ImageView getImageView(final int i) {
Bitmap bm = null;
if (i < itemList.size()) {
bm = decodeSampledBitmapFromUri(itemList.get(i), 220, 220);
}
ImageView imageView = new ImageView(myContext);
imageView.setLayoutParams(new LayoutParams(180, 220));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(bm);
/*ImageGalleryEdit.edit.setVisibility(View.GONE);
ImageGalleryEdit.delete.setVisibility(View.GONE);
*/
ImageGalleryEdit.viewimg.setImageBitmap(decodeSampledBitmapFromUri(itemList.get(i), 1220, 1220));
selectedfile = itemList.get(i);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ImageGalleryEdit.edit.setVisibility(View.VISIBLE);
ImageGalleryEdit.delete.setVisibility(View.VISIBLE);
ImageGalleryEdit.viewimg.setImageBitmap(decodeSampledBitmapFromUri(itemList.get(i), 1220, 1220));
selectedbm = decodeSampledBitmapFromUri(itemList.get(i), 1220, 1220);
selectedfile = itemList.get(i);
}
});
return imageView;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth,
int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
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;
}
}
Try to use fullScroll properties after fill data to horizontalscrollview :
hs.postDelayed(new Runnable() {
public void run() {
hs.fullScroll(View.FOCUS_RIGHT);
}
}, 100);

Outof memeory when display images in gridview

I have an activity which contains a gridview which is used to display the images by camera or gallery, however I found that it may cause OutOfMemory exception sometimes, this is the code codes, I am not sure what's the problem?
public class WaterPointSubmitActivity extends Activity {
private final int DIALOG_TYPE_IMAGE = 11;
private final int Result_Code_Camera = 11;
private final int Result_Code_Local = 12;
private final int Dialog_Source_Value_TakePhoto = 0; // the index in the array.xml
private final int Dialog_Source_value_Local = 1;
private ArrayList<String> mGridViewImages = new ArrayList<String>();
private GridView mGridView;
private ImageAdapter mGridViewAdapter;
private ImageView mImageAddButton;
private Uri mPhotoToBeUploadURI;
private AsyncHttpClient mAsyncHttpClient = Helper.getAsyncHttpClient();
private RequestHandle mCurrentRequset;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_point_submit);
this.setupViews();
}
private void setupViews() {
mGridView = (GridView) findViewById(R.id.images_grid_view);
mGridViewAdapter = new ImageAdapter(this, R.layout.common_expose_image_item, mGridViewImages);
mGridView.setAdapter(mGridViewAdapter);
//trigger the image choose dialog
mImageAddButton = (ImageView) findViewById(R.id.pollution_add_image);
mImageAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(DIALOG_TYPE_IMAGE);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
switch (id) {
case DIALOG_TYPE_IMAGE:
builder.setTitle(getString(R.string.dialog_choose_photo)).setItems(R.array.point_image_source, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case Dialog_Source_Value_TakePhoto:
//get image by camera
mPhotoToBeUploadURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoToBeUploadURI);
startActivityForResult(cameraIntent, Result_Code_Camera);
break;
case Dialog_Source_value_Local:
//from gallery
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, Result_Code_Local);
break;
}
}
});
Dialog target = builder.create();
target.setCanceledOnTouchOutside(false);
return target;
}
return null;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
if (resultCode == RESULT_OK) {
String imageFile = null;
switch (requestCode) {
case Result_Code_Camera:
String[] projection = {
MediaStore.MediaColumns._ID,
MediaStore.Images.ImageColumns.ORIENTATION,
MediaStore.Images.Media.DATA
};
Cursor c = getContentResolver().query(mPhotoToBeUploadURI, projection, null, null, null);
c.moveToFirst();
imageFile = c.getString(c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
break;
case Result_Code_Local:
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageFile = cursor.getString(columnIndex);
cursor.close();
break;
}
mGridViewImages.add(imageFile);
mGridViewAdapter.notifyDataSetChanged();
}
}
class ImageAdapter extends ArrayAdapter<String> {
private int mResourceId;
public ImageAdapter(Context context, int resource, List<String> items) {
super(context, resource, items);
mResourceId = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null || convertView.getTag() == null) {
convertView = getLayoutInflater().inflate(mResourceId, parent, false);
holder = new ViewHolder();
holder.pointImage = (ImageView) convertView.findViewById(R.id.pollution_image);
holder.pointDeleteImage = convertView.findViewById(R.id.pollution_image_delete);
convertView.setTag(holder);
holder.pointDeleteImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteImage(position);
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
String filePath = getItem(position);
if (filePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
holder.pointImage.setImageBitmap(bitmap);
}
return convertView;
}
}
private void deleteImage(int position) {
mGridViewImages.remove(position);
mGridViewAdapter.notifyDataSetChanged();
}
static class ViewHolder {
ImageView pointImage;
View pointDeleteImage;
}
}
What's the problem?
your view is loading full sized bitmaps causing OOM use BitmapFactory options to scale the bitmap before it is loaded into memory
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
options.inSampleSize = calculateInSampleSize(options,320,480);
options.inJustDecodeBounds = false;
Bitmap photo = BitmapFactory.decodeFile(selectedImagePath,options);
Helper Method
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
You just need to add this line to your manifest file....It will allocate the large memory for your application..
android:largeHeap="true"

Categories