I'm creating camera app. I'm doing that in fragment. I have FrameLayout where I add the camera, and one button for capture. There are 2 problems.
Camera not saves the image.
When I click second time on capture image, drops exception java.lang.RuntimeException: takePicture failed
I don't know where's the problem, I'm using camera API first time.
Camera I'm using only in portrait mode. And in manifests I added the permissions for camera and write external storage.
I have one class where I'm extending SurfaceView. Let me show you the code.
public class ShowCamera extends SurfaceView implements SurfaceHolder.Callback{
Camera camera;
SurfaceHolder holder;
public ShowCamera(Context context, Camera camera) {
super(context);
this.camera = camera;
holder = getHolder();
holder.addCallback(this);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
Camera.Parameters params = camera.getParameters();
List<Camera.Size> sizes = params.getSupportedPictureSizes();
Camera.Size mSize = null;
for (Camera.Size size : sizes){
mSize = size;
}
camera.setDisplayOrientation(90);
params.setRotation(90);
params.setPictureSize(mSize.width, mSize.height);
camera.setParameters(params);
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
camera.stopPreview();
camera.release();
}
}
Ok and here's the fragment for camera.
public class CameraActivity extends BaseFragment{
View mainView;
FrameLayout cameraLayout;
Camera camera;
ShowCamera showCamera;
ImageButton captureImage;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.camera_fragment, container, false);
cameraLayout = (FrameLayout) mainView.findViewById(R.id.cameraContainer);
captureImage = (ImageButton) mainView.findViewById(R.id.imageButton);
camera = Camera.open();
showCamera = new ShowCamera(getActivity(), camera);
cameraLayout.addView(showCamera);
capture();
return mainView;
}
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes, Camera camera) {
if(bytes != null){
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
if(bitmap != null){
File file = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)));
if(!file.isDirectory()){
file.mkdir();
}
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
System.currentTimeMillis() + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
}
};
public void capture(){
captureImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(camera != null){
camera.takePicture(null, null, mPictureCallback);
}
}
});
}
}
Related
In my app I'm using model class containing a Bitmap for displaying an image on recyclerView
public class ImageModelClass {
Bitmap image;
public void setImage(Bitmap image) {
this.image = image;
}
public Bitmap getImage() {
return image;
}
Problem is when i am using Bitmap directly from my model class then this error is throwing Error, cannot access an invalid/free'd bitmap here!
and when i replace the Bitmap Class to a String in my model class and using encoded bitmap i converted bitmap Image into a String then this error isn't coming .
But encoding a Bitmap is taking lot of time load images.
public class ImageCollection extends AppCompatActivity {
public static final String IMAGE_SHARED_PREFS = "com.example.animproject_IMAGE_SHARED_PREFS";
public static final String IMAGE_DATA_KEY = "com.example.animproject_IMAGE_DATA_KEY";
private static final int REQUEST_CODE = 1;
RecyclerView recyclerView;
ImageCollectionAdapter adapter;
List<ImageModelClass> imageList;
FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_collection);
loadAlbumData();
recyclerView = findViewById(R.id.imageCollectionRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
adapter = new ImageCollectionAdapter(this,imageList);
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, GridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
recyclerView.setAdapter(adapter);
fab = findViewById(R.id.fabButton);
fab.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK);
gallery.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
gallery.setType("image/*");
startActivityForResult(gallery, REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
assert data != null;
ClipData clipData = data.getClipData();
if (clipData != null) {
for (int i = 0; i < clipData.getItemCount(); i++) {
Uri imageUri = clipData.getItemAt(i).getUri();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
ImageModelClass imageModelClass = new ImageModelClass();
imageModelClass.setImage(bitmap);
imageList.add(imageModelClass);
adapter.notifyDataSetChanged();
saveGalleryData();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else {
Uri imageUri = data.getData();
InputStream inputStream = null;
try {
assert imageUri != null;
inputStream = getContentResolver().openInputStream(imageUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
ImageModelClass imageModelClass = new ImageModelClass();
imageModelClass.setImage(bitmap);
imageList.add(imageModelClass);
adapter.notifyDataSetChanged();
saveGalleryData();
}
}
}
private void saveGalleryData() {
SharedPreferences preferences = getSharedPreferences(IMAGE_SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(imageList);
editor.putString(IMAGE_DATA_KEY, json);
editor.apply();
}
private void loadAlbumData() {
SharedPreferences preferences = getSharedPreferences(IMAGE_SHARED_PREFS, MODE_PRIVATE);
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<ImageModelClass>>() {
}.getType();
String data = preferences.getString(IMAGE_DATA_KEY, null);
imageList = gson.fromJson(data, type);
if (imageList == null) {
imageList = new ArrayList<>();
}
}
}
Adapter
public class ImageCollectionAdapter extends RecyclerView.Adapter<ImageCollectionAdapter.MyViewHolder> {
List<ImageModelClass> list;
Context context;
public ImageCollectionAdapter(Context context,List<ImageModelClass> list) {
this.list = list;
this.context = context ;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.image_collection_lists, parent, false));
}
#Override
public void onBindViewHolder(#NonNull
MyViewHolder holder, int position) {
ImageModelClass currentImage =
list.get(position);
Glide
.With(context.getApplicationContext)
.load(currentImages.getImages)
/* getting bitmap images from model
* class
*/
.into(holder.imageView);
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
RoundedImageView imageView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.galleryPicture);
}
}
}
please help it will be appreciatable :)
I was facing the same issue when I was trying to get the bitmap from the textView. The textView was in the RecyclerView inside a bottom sheet. When I clicked on textView I was getting the bitmap and dismissing the bottom sheet.
I got the bitmap from the drawing cache of the textView. I checked it using the debugger the bitmap was retrieved correctly. But when I passed it to callback (from recyclerView's adapter to activity), the bitmap in the callback is not shown in the debugger and I got the error 'cannot access an invalid/free'd bitmap here!'.
As of my understanding, When textView is not shown/rendered on the screen (In my case when I dismissed the bottom sheet) the cached bitmap becomes unavailable. Gotta read the relevant docs to know the exact cause of the problem.
What I did to solve this issue is to create a copy of the bitmap and pass it to the callback and It worked!
You can copy the bitmap like this:
Bitmap copyBitmap = bitmap.copy(bitmap.getConfig(), false);
The full code of retrieving the bitmap and creating new one:
holder.textView.setDrawingCacheEnabled(true);
holder.textView.buildDrawingCache();
Bitmap bitmap = holder.textView.getDrawingCache();
Bitmap copyBitmap = bitmap.copy(bitmap.getConfig(), false);
holder.textView.setDrawingCacheEnabled(false);
callback.onWidgetSelected(copyBitmap);
I hope you'll find it helpful. I'll make sure to study the docs as well and will update the answer when I find the cause of this problem.
I want to make ocr application that can recognize text, but I just want to detect text only inside rectangle.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_transaksi, container, false);
cameraView = view.findViewById(R.id.surface_view);
txtView = view.findViewById(R.id.txtview);
mButton = view.findViewById(R.id.button1);
mButton.setOnClickListener(this);
txtRecognizer = new TextRecognizer.Builder(listener.getApplicationContext()).build();
detector = new FaceDetector.Builder(listener.getApplicationContext()).build();
cameraSource = new CameraSource.Builder(listener.getApplicationContext(), detector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(360 , 640)
.setRequestedFps(2.0f)
.setAutoFocusEnabled(true)
.build();
cameraView.getHolder().addCallback(this);
holder = cameraView.getHolder();
holder.addCallback((SurfaceHolder.Callback) this);
cameraView.setSecure(true);
transparentView = view.findViewById(R.id.transparent_view);
holderTransparent = transparentView.getHolder();
holderTransparent.addCallback((SurfaceHolder.Callback) this);
holderTransparent.setFormat(PixelFormat.TRANSLUCENT);
transparentView.setZOrderMediaOverlay(true);
deviceWidth=getScreenWidth();
deviceHeight=getScreenHeight();
return view;
}
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
private void Draw() {
Canvas canvas = holderTransparent.lockCanvas(null);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.GREEN);
paint.setStrokeWidth(3);
RectLeft = 40;
RectTop = 200 ;
RectRight = RectLeft+ deviceWidth-100;
RectBottom =RectTop+ 200;
Rect rec=new Rect((int) RectLeft,(int)RectTop,(int)RectRight,(int)RectBottom);
canvas.drawRect(rec,paint);
holderTransparent.unlockCanvasAndPost(canvas);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(listener,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(listener, new String[]{Manifest.permission.CAMERA},1);
return;
}
Draw();
cameraSource.start(cameraView.getHolder());
} catch (Exception e) {
e.printStackTrace();
}
}
I am new to android, I am making an app which can select and open multiple images from the gallery and can be viewed as slides. Then use paint canvas to draw on the images and record the whole screen.
I have managed to do all the parts except loading multiple images from the gallery into my app.
I can open images from drawable but finding difficulty to open from the gallery.
I am using ViewPager and fragment to open images from drawable, plz let me know a way to open multiple images from the gallery and show in my ViewPager.
page fragment class
package com.example.test2;
public class PageFragment extends Fragment {
private int imageResource;
private Bitmap bitmap;
public static PageFragment getInstance(int resourceID) {
PageFragment f = new PageFragment();
Bundle args = new Bundle();
args.putInt("image_source", resourceID);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageResource = getArguments().getInt("image_source");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_page, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ImageView imageView = (ImageView) view.findViewById(R.id.image);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 4;
o.inDither = false;
bitmap = BitmapFactory.decodeResource(getResources(), imageResource, o);
imageView.setImageBitmap(bitmap);
}
#Override
public void onDestroy() {
super.onDestroy();
bitmap.recycle();
bitmap = null;
}
}
viewPagerAdapter class
package com.example.test2;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Integer> images;
public ViewPagerAdapter(FragmentManager fm, List<Integer> imagesList) {
super(fm);
this.images = imagesList;
}
#Override
public Fragment getItem(int position) {
return PageFragment.getInstance(images.get(position));
}
#Override
public int getCount() {
return images.size();
}
}
MainActivity
package com.example.test2;
public class MainActivity extends AppCompatActivity {
ImageButton draw;
RelativeLayout relativeLayout;
Paint paint;
View view;
Path path2;
Bitmap bitmap;
Canvas canvas;
private ArrayList<Integer> images;
private BitmapFactory.Options options;
private ViewPager viewPager;
private View btnNext, btnPrev;
private FragmentStatePagerAdapter adapter;
private LinearLayout thumbnailsContainer;
private final static Integer[] resourceIDs = new Integer[]{R.mipmap.image7,R.mipmap.image6,R.mipmap.image5
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
images = new ArrayList<>();
//find view by id
viewPager = (ViewPager) findViewById(R.id.view_pager);
thumbnailsContainer = (LinearLayout) findViewById(R.id.container);
btnNext = findViewById(R.id.next);
btnPrev = findViewById(R.id.prev);
btnPrev.setOnClickListener(onClickListener(0));
btnNext.setOnClickListener(onClickListener(1));
setImagesData();
// init viewpager adapter and attach
adapter = new ViewPagerAdapter(getSupportFragmentManager(), images);
viewPager.setAdapter(adapter);
inflateThumbnails();
relativeLayout = (RelativeLayout) findViewById(R.id.layout);
draw= findViewById(R.id.b);
draw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setTitle("");
dialog.setContentView(R.layout.menu);
dialog.show();
Button black = dialog.findViewById(R.id.Black);
Button blue = dialog.findViewById(R.id.Blue);
Button red = dialog.findViewById(R.id.Red);
black.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
color();
paint.setColor(Color.parseColor("black"));
dialog.dismiss();
}
});
blue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
color();
paint.setColor(Color.parseColor("blue"));
dialog.dismiss();
}
});
red.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
color();
paint.setColor(Color.parseColor("red"));
dialog.dismiss();
}
});
}
});
}
private View.OnClickListener onClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i > 0) {
//next page
if (viewPager.getCurrentItem() < viewPager.getAdapter().getCount() - 1) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
} else {
//previous page
if (viewPager.getCurrentItem() > 0) {
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}
}
};
}
private void setImagesData() {
for (int i = 0; i < resourceIDs.length; i++) {
images.add(resourceIDs[i]);
}
}
private void inflateThumbnails() {
for (int i = 0; i < images.size(); i++) {
View imageLayout = getLayoutInflater().inflate(R.layout.item_image, null);
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.img_thumb);
imageView.setOnClickListener(onChagePageClickListener(i));
options = new BitmapFactory.Options();
options.inSampleSize = 3;
options.inDither = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),images.get(i),options);
imageView.setImageBitmap(bitmap);
//set to image view
imageView.setImageBitmap(bitmap);
//add imageview
thumbnailsContainer.addView(imageLayout);
}
}
private View.OnClickListener onChagePageClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(i);
}
};
}
public void color()
{
view = new SketchSheetView(MainActivity.this);
paint = new Paint();
path2 = new Path();
relativeLayout.addView(view, new ViewGroup.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
paint.setDither(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(6);
}
class SketchSheetView extends View {
public SketchSheetView(Context context) {
super(context);
bitmap = Bitmap.createBitmap(820, 480, Bitmap.Config.ARGB_4444);
canvas = new Canvas(bitmap);
this.setBackgroundColor(Color.TRANSPARENT);
}
private ArrayList<DrawingClass> DrawingClassArrayList = new ArrayList<DrawingClass>();
#Override
public boolean onTouchEvent(MotionEvent event) {
DrawingClass pathWithPaint = new DrawingClass();
canvas.drawPath(path2, paint);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
path2.moveTo(event.getX(), event.getY());
path2.lineTo(event.getX(), event.getY());
}
else if (event.getAction() == MotionEvent.ACTION_MOVE) {
path2.lineTo(event.getX(), event.getY());
pathWithPaint.setPath(path2);
pathWithPaint.setPaint(paint);
DrawingClassArrayList.add(pathWithPaint);
}
invalidate();
return true;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (DrawingClassArrayList.size() > 0) {
canvas.drawPath(
DrawingClassArrayList.get(DrawingClassArrayList.size() - 1).getPath(),
DrawingClassArrayList.get(DrawingClassArrayList.size() - 1).getPaint());
}
}
}
public class DrawingClass {
Path DrawingClassPath;
Paint DrawingClassPaint;
private Path getPath() {
return DrawingClassPath;
}
private void setPath(Path path) {
this.DrawingClassPath = path;
}
private Paint getPaint() {
return DrawingClassPaint;
}
private void setPaint(Paint paint) {
this.DrawingClassPaint = paint;
}
}
}
I'm not sure it's possible directly since to reach the gallery, you need to call an intent.
I suggest you to launch a method to retrieve photos in the gallery, following this example: enter link description here, to save all images into a list, and to display pictures in viewpager like you've aldready done.
I have this image adapter, that is supposed to handle updating a grid of images. The problem is that I have a BackgroundImageTask running that fetches the bitmap from a URL. The getView method returns the imageView before the Background Task can finish updating it. How Can I force the Background Task to finish before it returns the imageview?
public class ImageAdapter extends BaseAdapter {
private Context mContext;
Bitmap bitmap;
List<Post> postList;
ImageView imageView;
int pos;
public ImageAdapter(Context c, List<Post> p) {
mContext = c;
postList = p;
}
public int getCount() {
return postList.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
pos=position;
View convert = convertView;
if (convert == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, 320));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convert;
}
new BackgroundImageTask().execute();
return imageView;
}
public View SetBit(Bitmap b){
imageView.setImageBitmap(b);
return imageView;
}
class BackgroundImageTask extends AsyncTask<Void, Void, Bitmap> {
#Override
protected Bitmap doInBackground(Void... params) {
Bitmap bit1=bitmap;
try {
bit1 = BitmapFactory.decodeStream((InputStream)new URL(postList.get(pos).thumbnail).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bit1;
}
#Override
protected void onPostExecute(Bitmap bit) {
SetBit(bit);
}
}
}
Instead You can pass the ImageView Object to the background Task like
new BackgroundImageTask(imageView).execute();
and
class BackgroundImageTask extends AsyncTask<Void, Void, Bitmap> {
ImageView iv;
BackgroundImageTask(ImageView imageView){
iv = imageView;
}
#Override
protected Bitmap doInBackground(Void... params) {
Bitmap bit1=bitmap;
try {
bit1 = BitmapFactory.decodeStream((InputStream)new URL(postList.get(pos).thumbnail).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bit1;
}
#Override
protected void onPostExecute(Bitmap bit) {
iv.setImageBitmap(bit);
}
}
I have an activity with some photos, and I'm using ViewPager for swiping those photos. How can I show some transparent image at the activity start, just to show some instructions for swipe and stuff, like ES File Explorer did it on the image below? I have and image, transparent like the one below. I want to show it on top of my first image, and the user can swipe it.
Here's my class:
public class Photo_gallery extends Activity implements OnClickListener{
Button save;
Context mContext;
final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Images/");
boolean success = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
mContext = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_gallery);
save = (Button) findViewById(R.id.bSave);
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
final String fname = "StyleMe-" + 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/Pictures/SexyImages",
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://"
+ Environment.getExternalStorageDirectory())));
}
});
}
public class ImagePagerAdapter extends PagerAdapter {
public int[] mImages = new int[] {
R.drawable.p1,
R.drawable.p2,
R.drawable.p3,
.
.
.
R.drawable.p108
};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Photo_gallery.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
The simplest solution is probably to use the ShowcaseView library for this.