Changing an ImageView to black and white - android

I would like to change an ImageView's image to black and white. The only thing is my code allows the user to take a photo, that photo is placed in the imageview. I would like that photo to be black and white. If anyone knows how I could do this, I would appreciate it.
MainActivity:
package com.example.triptych4;
import java.io.File;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
// label our logs "CameraApp3"
private static String logtag = "CameraApp3";
// tells us which camera to take a picture from
private static int TAKE_PICTURE = 1;
// empty variable to hold our image Uri once we store it
private Uri imageUri;
private Integer[] pics = { R.drawable.android, R.drawable.android3d,
R.drawable.background3 };
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
imageView = (ImageView) findViewById(R.id.imageView1);
gallery.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(), "pic:" + arg2,
Toast.LENGTH_SHORT).show();
imageView.setImageResource(pics[arg2]);
}
});
// look for the button we set in the view
ImageButton cameraButton = (ImageButton)
findViewById(R.id.button_camera);
// set a listener on the button
cameraButton.setOnClickListener(cameraListener);
}
// set a new listener
private OnClickListener cameraListener = new OnClickListener() {
public void onClick(View v) {
// open the camera and pass in the current view
takePhoto(v);
}
};
public void takePhoto(View v) {
// tell the phone we want to use the camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// create a new temp file called pic.jpg in the "pictures" storage area of the phone
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "pic.jpg");
// take the return data and store it in the temp file "pic.jpg"
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
// stor the temp photo uri so we can find it later
imageUri = Uri.fromFile(photo);
// start the camera
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class ImageAdapter extends BaseAdapter{
private Context context;
int imageBackground;
public ImageAdapter(Context context){
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pics.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView imageView =new ImageView(context);
imageView.setImageResource(pics[arg0]);
return imageView;
}
}
// override the original activity result function
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// call the parent
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
// if the requestCode was equal to our camera code (1) then...
case 1:
// if the user took a photo and selected the photo to use
if(resultCode == Activity.RESULT_OK) {
// get the image uri from earlier
Uri selectedImage = imageUri;
// notify any apps of any changes we make
getContentResolver().notifyChange(selectedImage, null);
// get the imageView we set in our view earlier
ImageButton imageButton = (ImageButton)findViewById(R.id.button_camera);
// create a content resolver object which will allow us to access the image file at the uri above
ContentResolver cr = getContentResolver();
// create an empty bitmap object
Bitmap bitmap;
try {
// get the bitmap from the image uri using the content resolver api to get the image
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
// set the bitmap to the image view
imageButton.setImageBitmap(bitmap);
// notify the user
Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_LONG).show();
} catch(Exception e) {
// notify the user
Toast.makeText(MainActivity.this, "failed to load", Toast.LENGTH_LONG).show();
Log.e(logtag, e.toString());
}
}
}
}
}
Layout:
<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"
tools:context="com.example.triptych5.MainActivity" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="200dp"
android:layout_height="200dp"
android:scaleType="fitXY"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/button_camera"/>
<ImageButton
android:id="#+id/button_camera"
android:layout_width="230dp"
android:layout_height="235dp"
android:scaleType="fitXY"
android:rotation="-90"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/middle4" />
<Gallery
android:id="#+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/imageView1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>

You can simply achieve this by doing:
ImageView imageview = (ImageView) findViewById(R.id.imageView1);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
imageview.setColorFilter(filter);

This is the Kotlin Version
imageView.colorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0f)})

You can use android.graphics.ColorFilter for your purpose.
You can use this sample to suite your need.
Pass the imageView to the setBW method like
setBW(imageView);
and the the functionality is
private void setBW(ImageView iv){
float brightness = 10; // change values to suite your need
float[] colorMatrix = {
0.33f, 0.33f, 0.33f, 0, brightness,
0.33f, 0.33f, 0.33f, 0, brightness,
0.33f, 0.33f, 0.33f, 0, brightness,
0, 0, 0, 1, 0
};
ColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
iv.setColorFilter(colorFilter);
}
Try using this. Any concerns. Let me know. Thanks.

I would also suggest using Kotlin extensions:
private const val MAX_SATURATION = 1f
private const val MIN_SATURATION = 0f
fun ImageView.setMaxSaturation() {
val matrix = ColorMatrix()
matrix.setSaturation(MAX_SATURATION)
colorFilter = ColorMatrixColorFilter(matrix)
}
fun ImageView.setMinSaturation() {
val matrix = ColorMatrix()
matrix.setSaturation(MIN_SATURATION)
colorFilter = ColorMatrixColorFilter(matrix)
}

Java version in one line
imageview.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(){{setSaturation(0f);}}));

Related

Syntax error on token(s) on line of code

i'm getting an error on one of the lines of code that I can't seem to find the solution.
The error is on this line:
cameraButton.setOnClickListener(cameraListener);
The error im getting is "Syntax error on token(s)
MainActivity
package com.example.triptych4;
import java.io.File;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
// label our logs "CameraApp3"
private static String logtag = "CameraApp3";
// tells us which camera to take a picture from
private static int TAKE_PICTURE = 1;
// empty variable to hold our image Uri once we store it
private Uri imageUri;
private Integer[] pics = { R.drawable.android, R.drawable.android3d,
R.drawable.background3 };
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
//create adapter Gallery
gallery.setAdapter(new ImageAdapter(this));
imageView = (ImageView) findViewById(R.id.imageView1);
gallery.setOnItemClickListener(new onItemClickListener() {
#Oveerride
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "pic:" + arg2, Toast.LENGTH_SHORT).show();
imageView.setImageResource(pics[arg2]);
}
// look for the button we set in the view
ImageButton cameraButton = (ImageButton)
findViewById(R.id.button_camera);
// set a listener on the button
cameraButton.setOnClickListener(cameraListener);
}
// set a new listener
private OnClickListener cameraListener = new OnClickListener() {
public void onClick(View v) {
// open the camera and pass in the current view
takePhoto(v);
}
};
public void takePhoto(View v) {
// tell the phone we want to use the camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// create a new temp file called pic.jpg in the "pictures" storage area of the phone
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "pic.jpg");
// take the return data and store it in the temp file "pic.jpg"
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
// stor the temp photo uri so we can find it later
imageUri = Uri.fromFile(photo);
// start the camera
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class ImageAdapter extends BaseAdapter{
private Context context;
int imageBackground;
public ImageAdapter(Context context){
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pics.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView imageView =new ImageView(context);
imageView.setImageResource(pics[arg0]);
return imageView;
}
}
// override the original activity result function
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// call the parent
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
// if the requestCode was equal to our camera code (1) then...
case 1:
// if the user took a photo and selected the photo to use
if(resultCode == Activity.RESULT_OK) {
// get the image uri from earlier
Uri selectedImage = imageUri;
// notify any apps of any changes we make
getContentResolver().notifyChange(selectedImage, null);
// get the imageView we set in our view earlier
ImageButton imageButton = (ImageButton)findViewById(R.id.button_camera);
// create a content resolver object which will allow us to access the image file at the uri above
ContentResolver cr = getContentResolver();
// create an empty bitmap object
Bitmap bitmap;
try {
// get the bitmap from the image uri using the content resolver api to get the image
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
// set the bitmap to the image view
imageButton.setImageBitmap(bitmap);
// notify the user
Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_LONG).show();
} catch(Exception e) {
// notify the user
Toast.makeText(MainActivity.this, "failed to load", Toast.LENGTH_LONG).show();
Log.e(logtag, e.toString());
}
}
}
}
}
You're missing some braces and semicolons, and you've got an #Oveerride in there as well.
Try this, it should compile:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
//create adapter Gallery
gallery.setAdapter(new ImageAdapter(this));
imageView = (ImageView) findViewById(R.id.imageView1);
gallery.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "pic:" + arg2, Toast.LENGTH_SHORT).show();
imageView.setImageResource(pics[arg2]);
}
});
// look for the button we set in the view
ImageButton cameraButton = (ImageButton)
findViewById(R.id.button_camera);
// set a listener on the button
cameraButton.setOnClickListener(cameraListener);
}

saving and then displaying camera photo on application

I'm trying to make a android app that will take a picture from the camera and display it on the same screen next to the "take picture button". I've been trying to use a tutorial but it is not working. whenever I take the picture and press save, the picture app fails. Also I don't know if it would display the photo on screen if I saved it. However, I am not sure of this since it always breaks after I press save.
Does anybody have any suggestions to help me save and display the photo on screen?
Thanks
Here's my xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.pictureproject.MainActivity"
android:orientation ="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button_camera"
android:text="#string/button_camera"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ImageView
android:id = "#+id/image_camera"
android:contentDescription="#string/image_cd_camera"
android:layout_width="fill_parent"
android:layout_height = "wrap_content"
/>
</LinearLayout>
and Heres my java:
package com.example.pictureproject;
import java.io.File;
import android.app.Activity;
import android.content.ContentResolver;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private static String logtag ="CameraApp8";
private static int TAKE_PICTURE = 1;
private Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button cameraButton = (Button)findViewById(R.id.button_camera);/*possibly button camera 1*/
cameraButton.setOnClickListener(cameraListener);
}
private OnClickListener cameraListener = new OnClickListener() {
public void onClick(View v){
takePhoto(v);
}
};
private void takePhoto(View v){
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"picture.jpg");
imageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
if(resultCode == Activity.RESULT_OK){
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView)findViewById(R.id.image_camera);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try{
bitmap = MediaStore.Images.Media.getBitmap(cr,selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this, selectedImage.toString(),Toast.LENGTH_LONG).show();
}catch(Exception e){
Log.e(logtag,e.toString());
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
try to add this code..
public class MyCameraActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}

how to save ViewPager Current image to sd card on button click

i am working on a image swipe app in which i am swiping images on ViewPager and i want to save current showing image to sd card on button click.
my code: SwipeActivity.java
package com.td.gridview;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
public class SwipeActivity extends Activity {
protected int curruntPosition;
protected int hh;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.swipe_view);
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
// Here you can set the wallpaper
curruntPosition = arg0;
if (curruntPosition == arg0) {
hh = 1;
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
//
Button bx = (Button) findViewById(R.id.xoom);
bx.setOnClickListener(new View.OnClickListener() {
public void onClick(View vx) {
// // TODO Auto-generated method stub
if (hh == 1) {
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Full_Zoom.class);
// passing array index
i2.putExtra("id", curruntPosition);
startActivity(i2);
} else {
// get intent data
Intent i3 = getIntent();
// Selected image id
int position = i3.getExtras().getInt("id");
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Full_Zoom.class);
// passing array index
i2.putExtra("id", position);
startActivity(i2);
}
}
});
//
// Save ViewPager current image to sd card on button click
Button b1 = (Button) findViewById(R.id.wll);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v2) {
// // TODO Auto-generated method stub
// Save ViewPager current image to sd card
}
});
}
public class ImagePagerAdapter extends PagerAdapter {
int[] icons = MainActivity.ICONS;
#Override
public int getCount() {
return icons.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = SwipeActivity.this;
ImageView imageView = new ImageView(context);
// int padding = context.getResources().getDimensionPixelSize(
// R.dimen.padding_large);
// imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(icons[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
in this above code find this code: here i want to perform save image from viewpager to sd card
// Save ViewPager current image to sd card on button click
Button b1 = (Button) findViewById(R.id.wll);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v2) {
// // TODO Auto-generated method stub
// Save ViewPager current image to sd card
}
});
Try something like this:
String filename;
Bitmap imageBitmap;
//....
//set file name and bitmap
//....
File imageFile = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream out;
try {
out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
outStream.flush();
outStream.close();
success = true;
} catch (Exception e) {
Log.e(TAG, "Error writing to file: ", e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
Log.e(TAG, "Error closing file: ", e);
}
}
}
i found my answer:
package com.td.gridview;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class SwipeActivity extends Activity {
Context mContext;
//set save file location example: .getAbsolutePath() + "/Pictures");
final File myDir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/");
boolean success = false;
protected int curruntPosition;
protected int hh;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.swipe_view);
final Context mContext;
mContext = this;
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
// Here you can set the wallpaper
curruntPosition = arg0;
if (curruntPosition == arg0) {
hh = 1;
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
//
Button bx = (Button) findViewById(R.id.xoom);
bx.setOnClickListener(new View.OnClickListener() {
public void onClick(View vx) {
// // TODO Auto-generated method stub
if (hh == 1) {
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Full_Zoom.class);
// passing array index
i2.putExtra("id", curruntPosition);
startActivity(i2);
} else {
// get intent data
Intent i3 = getIntent();
// Selected image id
int position = i3.getExtras().getInt("id");
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Full_Zoom.class);
// passing array index
i2.putExtra("id", position);
startActivity(i2);
}
}
});
//
// Save ViewPager current image to sd card on button click
Button b1 = (Button) findViewById(R.id.wll);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v2) {
// // TODO Auto-generated method stub
// Save ViewPager current image to sd card
//
final Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
final String fname = "temp_image" + n + ".png";
myDir.mkdirs();
File image = new File(myDir, fname);
int currentItem = viewPager.getCurrentItem();
Drawable drawable = mContext.getResources().getDrawable(
adapter.mImages[currentItem]);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(),
"Image saved with success at /sdcard/temp_image",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG)
.show();
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
.parse("file://mnt/sdcard/"
+ Environment.getExternalStorageDirectory())));
}
//
});
}
public class ImagePagerAdapter extends PagerAdapter {
protected int[] mImages = MainActivity.ICONS;
int[] icons = MainActivity.ICONS;
#Override
public int getCount() {
return icons.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = SwipeActivity.this;
ImageView imageView = new ImageView(context);
// int padding = context.getResources().getDimensionPixelSize(
// R.dimen.padding_large);
// imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(icons[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}

Image fails to display

I want to display an image using a file path .
/mnt/sdcard/DCIM/Camera/IMG_20140524_150944.jpg
Here is the layout file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/item_single_new"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dip"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"/>
</LinearLayout>
Here is the code i am using.
package com.bridge.bridgeinventory;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
public class SingleImage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_image);
ImageView image = (ImageView)
findViewById(R.id.item_single_new);
image.setAdjustViewBounds(true);
image.setMaxHeight(100);
image.setMaxWidth(100);
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
Intent i=getIntent();
String myimage =i.getStringExtra("photo").trim();
Log.e("image path", myimage);
Bitmap m= BitmapFactory.decodeFile(myimage);
if(m==null)
{
Toast.makeText(getApplicationContext(), "Image was deleted", Toast.LENGTH_LONG).show();
}
image.setImageBitmap(m);
}
}
The intent extral prints out correctly(as shown above) but the image does not display.
I only see a black patch instead of the image.
Is there anything simple i am missing?
This was supposed to be something simple but it has completely defeated me!
Ronald
This is how i get the path to store in the db.
public void GetPhoto(View v)
{
Intent picintent= new Intent(Intent.ACTION_PICK);
picintent.setType("image/*");
startActivityForResult(picintent,GET_PHOTO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if(requestCode==GET_PHOTO){
if (resultData != null) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
String imagePath = cursor.getString(column_index_data);
cursor.close();
bridgephoto=imagePath;
Log.e("imagepath", bridgephoto);
}
}
}
The bridgephoto variable is a class level variable
After getting from the intent, i use it to set the photo proprty like below.
bridge.setBridgePhoto(bridgephoto);
Then i have a listview that displays the bridges . It has an a context menu with an option to display the bridge photo.
Here is the code for the photo menu item
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
int menuItemIndex = item.getItemId();
String menuItemName =menuitems[menuItemIndex];
final AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item
.getMenuInfo();
final int pos = menuInfo.position;
if(menuItemName=="Photo")
{
Bridge b= (Bridge)ba.getItem(pos);
String image=b.getBridgePhoto();
/// put it in an intent!
Intent i= new Intent(Bridges.this,SingleImage.class);
i.putExtra("photo",image);
startActivity(i);
}
return super.onMenuItemSelected(featureId, item);
}
It is the string extral that is passed to the SingleImage activity.
But i have used Log.e to test the string(image path) and it appears correct.

Android: Orientation changes erase modifications made to my ImageView

I have app in which I have ImageView. I open new activity, where I paint something by finger and this bitmap return to my ImageView. everything is ok but when I change orientation now, my activity with ImageView is repaint or restart and imageview is empty. I try everything, I try SaveState and restore state, try configurationChange, and other, but nothing is working...
package jilova.Android.TextFolder;
import java.io.ByteArrayOutputStream;
import jilova.Android.Enums;
import jilova.Android.R;
import jilova.Android.DatabaseFolder.LocalDB;
import jilova.Android.DatabaseFolder.RequestRow;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Toast;
public class Text extends Activity{
private static EditText t1;
private static EditText t2;
private static EditText t3;
private static EditText t4;
private static ImageView iv1;
private static Context c;
private static Activity ac;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
Object o = this.getLastNonConfigurationInstance();
if(o!=null)
{
Enums.sign=(Bitmap)o;
}
c=this.getApplicationContext();
ac=this;
ImageView iv = (ImageView)this.findViewById(R.id.imageView1);
iv.setDrawingCacheEnabled(true);
t1 = (EditText)this.findViewById(R.id.TEXTNote);
t2 = (EditText)this.findViewById(R.id.TextET2);
t3 = (EditText)this.findViewById(R.id.TextET3);
t4 = (EditText)this.findViewById(R.id.TextET4);
//iv.setImageBitmap(Bitmap.createScaledBitmap(Enums.sign, iv.getWidth(), iv.getHeight(), false).copy(Config.ARGB_8888, true));
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
}
// Checks whether a hardware keyboard is available
if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
} else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
}
}
public static RequestRow getData()
{
RequestRow row = new RequestRow();
row.SetREQUESTNOTE(t1.getText().toString());
row.SetREQUESTTYPEID(Integer.parseInt(t2.getTag().toString()));
row.SetTYPTECHUDRZBYID(Integer.parseInt(t3.getTag().toString()));
row.SetOBJECTID(Integer.parseInt(t4.getTag().toString()));
return row;
}
public static void setData(String REQUESTTYPEID ,String TYPTECHUDRZBYID,String OBJECTID,String REQUESTNOTE,String REQUESTID)
{
t1.setText(REQUESTNOTE);
t2.setTag(REQUESTTYPEID);
t2.setText(LocalDB.dbGetRequestTypeByID(c, Integer.parseInt(REQUESTTYPEID)));
t3.setTag(TYPTECHUDRZBYID);
t3.setText(LocalDB.dbGetTypTechUdrzbyByID(c, Integer.parseInt(TYPTECHUDRZBYID)));
t4.setTag(OBJECTID);
t4.setText(LocalDB.dbGetObjectByID(c, Integer.parseInt(OBJECTID)));
Bitmap b = LocalDB.dbGetDocumentByID(c, Integer.parseInt(REQUESTID));
if(b!=null)
{
iv1.setImageBitmap(b);
}
}
public static Bitmap getSign()
{
iv1.buildDrawingCache();
Bitmap ret = iv1.getDrawingCache();
if(Enums.EmptySignHash)
{
return null;
}
else
{
return ret;
}
}
public void Sign(View button)
{
Intent s = new Intent(Text.this,Sign.class);
startActivityForResult(s,Enums.SIGNREQUESTID);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode!=Activity.RESULT_OK)
{
return;
}
Enums.IDLocal=-1;
if(requestCode==Enums.GetData)
{
Bundle extras = data.getExtras();
if(extras !=null)
{
EditText et = (EditText)this.findViewById(extras.getInt("ViewID"));
et.setText(extras.getString("Value"));
et.setTag(extras.get("ID"));
}
}
else if(requestCode==Enums.SIGNREQUESTID)
{
Bundle extras = data.getExtras();
if(extras !=null)
{
ImageView iv = (ImageView)this.findViewById(R.id.imageView1);
try
{
byte[] b = extras.getByteArray("Bitmap");
Enums.sign = Bitmap.createBitmap(BitmapFactory.decodeByteArray(b, 0, b.length), 0, 0, ac.getWindowManager().getDefaultDisplay().getWidth(), 200);
iv.setImageBitmap(Bitmap.createScaledBitmap(Enums.sign, iv.getWidth(), iv.getHeight(), false));
}
catch(Exception e)
{
int a=0;
}
}
Enums.EmptySignHash=false;
}
}
public static void DeleteAll()
{
EditText t = (EditText)ac.findViewById(R.id.TEXTNote);
t.setText("");
t.setTag(-1);
t = (EditText)ac.findViewById(R.id.TextET2);
t.setText("");
t.setTag(-1);
t = (EditText)ac.findViewById(R.id.TextET3);
t.setText("");
t.setTag(-1);
t = (EditText)ac.findViewById(R.id.TextET4);
t.setText("");
t.setTag(-1);
ImageView iv = (ImageView)ac.findViewById(R.id.imageView1);
//Bitmap b = Bitmap.createBitmap(Enums.createColors(), 0, Enums.STRIDE, Enums.WIDTH, Enums.HEIGHT, Bitmap.Config.ARGB_8888).copy(Bitmap.Config.ARGB_8888, true);
iv.setImageBitmap(Bitmap.createScaledBitmap(Enums.sign, ac.getWindowManager().getDefaultDisplay().getWidth(), iv.getLayoutParams().height, false));
Enums.EmptySignHash=true;
}
public void Delete(View button)
{
EditText t = (EditText)this.findViewById(R.id.TEXTNote);
t.setText("");
t.setTag(-1);
t = (EditText)this.findViewById(R.id.TextET2);
t.setText("");
t.setTag(-1);
t = (EditText)this.findViewById(R.id.TextET3);
t.setText("");
t.setTag(-1);
t = (EditText)this.findViewById(R.id.TextET4);
t.setText("");
t.setTag(-1);
ImageView iv = (ImageView)this.findViewById(R.id.imageView1);
//Bitmap b = Bitmap.createBitmap(Enums.createColors(), 0, Enums.STRIDE, Enums.WIDTH, Enums.HEIGHT, Bitmap.Config.ARGB_8888).copy(Bitmap.Config.ARGB_8888, true);
iv.setImageBitmap(Bitmap.createScaledBitmap(Enums.sign, ac.getWindowManager().getDefaultDisplay().getWidth(), iv.getLayoutParams().height, false));
Enums.EmptySignHash=true;
}
public void GetData(View button)
{
if(button.getId()==R.id.TextIB3)
{
Intent ChooseAction = new Intent(Text.this,ChooseData.class);
Enums.Data = LocalDB.dbLocalSelect(this.getApplicationContext(),"Select typtechudrzbyid,typtechudrzbydesc from typtechudrzby");
if(Enums.Data==null)
{
Toast t=Toast.makeText(this, "Chyba lokalni db", Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
return;
}
ChooseAction.putExtra("ViewID", R.id.TextET3);
startActivityForResult(ChooseAction,Enums.GetData);
}
else if(button.getId()==R.id.TextIB2)
{
Intent ChooseAction = new Intent(Text.this,ChooseData.class);
Enums.Data = LocalDB.dbLocalSelect(this.getApplicationContext(),"Select Requesttypeid,requestname from requesttype");
if(Enums.Data==null)
{
Toast t=Toast.makeText(this, "Chyba lokalni db", Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
return;
}
ChooseAction.putExtra("ViewID", R.id.TextET2);
startActivityForResult(ChooseAction,Enums.GetData);
}
else if(button.getId()==R.id.TextIB4)
{
Intent ChooseAction = new Intent(Text.this,TreeData.class);
Enums.TreeData = LocalDB.dbLocalSelectTree(this.getApplicationContext(),"Select objectid,objectname,objectref from Objects");
if(Enums.TreeData==null)
{
Toast t=Toast.makeText(this, "Chyba lokalni db", Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
return;
}
ChooseAction.putExtra("ViewID", R.id.TextET4);
startActivityForResult(ChooseAction,Enums.GetData);
}
else
{
//throw new Exception();
}
}
}
When a configuration change such as a screen rotation occurs by default your Activity is destroyed and then recreated (onDestroy of the current activity is called, and then the onCreate of a new version of your activity is called).
You can either:
Stop Android recreating your activity when a configuration change occurs. To do this add android:configChanges="keyboardHidden|orientation" to the activity tag in your manifest. This is not recommend since if you want a different layout etc for different configurations you will have to handle changing the layout yourself.
Override onRetainNonConfigurationInstance and return your bitmap from that. In onCreate check if the last non-configuration instance is not null, in which case cast it to a bitmap and then set the image.
For the latter case, use something like the following:
#Override
public void onCreate(Bundle savedInstanceState) {
...
// Check if our activity was just destroyed and re-created
final Object retainedFromConfigChange = getLastNonConfigurationInstance();
if (retainedFromConfigChange != null) {
// Activity has just been recreated, get the image we were working on
// before the configuration change
ImageView iv = (ImageView)ac.findViewById(R.id.imageView1);
iv.setImageBitmap((Bitmap) retainedFromConfigChange);
}
...
}
#Override
public Object getLastNonConfigurationInstance() {
ImageView iv = (ImageView)ac.findViewById(R.id.imageView1);
// We have to return a plain old Bitmap and not a drawable of any sorts
// or we will get memory leaks so we need to extract the bitmap from the drawable
return ((BitmapDrawable) iv.getDrawable()).getBitmap();
}
I think you forgot to override the onRetainNonConfigurationInstance() method where you return your bitmap so it will be passed to the new activity. In the new activity you can retrieve the bitmap as you already do by calling getLastNonConfigurationInstance().
When the configuration is changed, the whole view is re-created. So, we need to retain the imageView resource. The best way to do this is to handle the orientation change by creating a Retained fragment.
You can find the perfect documentation on Android developer's page.
P.S.: Adding android:configChanges="keyboardHidden|orientation" to the manifest is highly not recommended.

Categories

Resources