Passing bitmap object to Mainactivity - java

i have a service in which my camera is taking a picture. Here is the code:
public class Picture_Service extends Service
{
//Camera variables
//a surface holder
private SurfaceHolder sHolder;
//a variable to control the camera
private Camera mCamera;
//the camera parameters
private Parameters parameters;
private int i = 0;
private static final int DISCOVER_DURATION = 300;
// our request code (must be greater than zero)
private static final int REQUEST_BLU = 1;
/** Called when the activity is first created. */
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
mCamera = Camera.open();
SurfaceView sv = new SurfaceView(getApplicationContext());
try {
mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
//set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "Logged in as Administrator!",Toast.LENGTH_LONG).show();
Log.w("Display Hona Chahye", "Kr dia na display Rami");
e.printStackTrace();
}
//Get a surface
sHolder = sv.getHolder();
//tells Android that this surface will have its data constantly replaced
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
//decode the data obtained by the camera into a Bitmap
FileOutputStream outStream = null;
try{
i++;
Log.w("Rami Rami","maha harami");
Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data.length);
//outStream = new FileOutputStream("/sdcard/Image.jpg");
//outStream.write(data);
//Bitmap yourSelectedImage = BitmapFactory.decodeFile("/sdcard/Image.jpg");
//BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
Log.w("Rami insan","Rami write hogya");
mCamera.release();
outStream.close();
} catch (FileNotFoundException e){
Log.d("CAMERA", e.getMessage());
} catch (IOException e){
Log.d("CAMERA", e.getMessage());
}
}
};
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
1- My first question is would i get my image in the bitmap object here: ?
Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data.length);
2- Secondly, i want to pass this object to the mainactivity. How will i do that??

You can convert your image to a String and pass it to MainActivity.
convert your image into a byte array though. Here's an example:
Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
And encode it to base64 :
String encodedImage = Base64.encodeToString(byte, Base64.DEFAULT);
byte[] bytearray = Base64.decode(encodedImage);
FileOutputStream imageOutFile = new FileOutputStream("after_convert.jpg");
imageOutFile.write(bytearray);

Related

How can I take Screenshots using Arcore?

I am trying to take a screenshot of my Augmented Reality Screen and pass it as a bitmap to another activity.
This is the code that I am using to take the screenshot:
Function to take screen shot
public static void tmpScreenshot(Bitmap bmp, Context context){
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bmp.recycle();
//Pop intent
Intent in1 = new Intent(context, CostActivity.class);
in1.putExtra("image", filename);
context.startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
}
Function to receive screenshot
private void loadTmpBitmap() {
Bitmap bmp = null;
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
ImageView imageView = findViewById(R.id.test);
imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, 120, 120, false));
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Even though the Screenshot was taken, it was black when it is passed to another activity.
In addition, the Screenshot only appeared after I pressed the back button
Can anyone help me with the code to take a screenshot with ARCore? Or what am I doing wrong?
It is not possible to take a screenshot of a SurfaceView using your method. If you do then the screenshot will be black, as it only works for regular views.
What you need to use is pixelcopy.
private void takePhoto() {
ArSceneView view = arFragment.getArSceneView();
// Create a bitmap the size of the scene view.
final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
Bitmap.Config.ARGB_8888);
// Create a handler thread to offload the processing of the image.
final HandlerThread handlerThread = new HandlerThread("PixelCopier");
handlerThread.start();
// Make the request to copy.
PixelCopy.request(view, bitmap, (copyResult) -> {
if (copyResult == PixelCopy.SUCCESS) {
try {
saveBitmapToDisk(bitmap);
} catch (IOException e) {
Toast toast = Toast.makeText(VisualizerActivity.this, e.toString(),
Toast.LENGTH_LONG);
toast.show();
return;
}
SnackbarUtility.showSnackbarTypeLong(settingsButton, "Screenshot saved in /Pictures/Screenshots");
} else {
SnackbarUtility.showSnackbarTypeLong(settingsButton, "Failed to take screenshot");
}
handlerThread.quitSafely();
}, new Handler(handlerThread.getLooper()));
}
public void saveBitmapToDisk(Bitmap bitmap) throws IOException {
// String path = Environment.getExternalStorageDirectory().toString() + "/Pictures/Screenshots/";
if (videoDirectory == null) {
videoDirectory =
new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/Screenshots");
}
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
String formattedDate = df.format(c.getTime());
File mediaFile = new File(videoDirectory, "FieldVisualizer"+formattedDate+".jpeg");
FileOutputStream fileOutputStream = new FileOutputStream(mediaFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}

Image is not getting clear captured by custom camera in android

I am creating a multi-image capturing feature using custom Camera in my app.But there is a problem with the custom camera. Image captured by custom camera is not getting clear as like default camera(Camera opening with Intent)
Please help me out.I have tried the lot of suggested solutions.
CameraActivity.java
public class CameraActivity extends Activity {
private Camera mCamera;
private SharedPreferences prefs;
private String clickedMenuItem;
Button captureButton;
private LayoutInflater controlInflater = null;
private View viewControl;
private CircularImageView imgview;
private ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();;
private ImageView cancleimg;
private FrameLayout imgLayout;
int RESULT_IMG = 200;
int NO_IMG = 204;
FrameLayout preview;
private CameraPreview mCameraPreview;
ArrayList<CharSequence> imgarrayList = new ArrayList<CharSequence>();
Intent intent = new Intent( );
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_preview);
clickedMenuItem = Attributes.Another_Item;
if(getIntent().hasExtra(Attributes.ClickedMenuItem)){
clickedMenuItem = getIntent().getExtras().getString(Attributes.ClickedMenuItem);
}
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
try{
controlInflater = LayoutInflater.from(getBaseContext());
viewControl = controlInflater.inflate(R.layout.control, null);
LayoutParams layoutParamsControl
= new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
}catch(Exception e)
{e.printStackTrace();}
captureButton = (Button)viewControl.findViewById(R.id.button_capture);
Button doneBtn = (Button)viewControl.findViewById(R.id.done);
imgview = (CircularImageView)viewControl.findViewById(R.id.captureimg);
cancleimg = (ImageView)viewControl.findViewById(R.id.cancleimg);
imgLayout = (FrameLayout)viewControl.findViewById(R.id.imglayout);
imgLayout.setVisibility(View.INVISIBLE);
if (isDIYUSer() && clickedMenuItem != null && !clickedMenuItem.equals(Attributes.Kagazz_Scanner)) {
captureButton.setBackgroundResource(R.drawable.cam);
}
cancleBtnClick();
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
setResult(RESULT_IMG,intent);
bitmapArray = null;
finish();
}
});
}
#Override
public void onPause() {
try{
super.onPause();
releaseCamera();
}catch(Exception e)
{}// release the camera immediately on pause event
}
private void releaseCamera(){
try{
if (mCamera != null){
mCamera.stopPreview();
mCamera.setPreviewCallback(null);// stop the preview
mCamera.release();
preview.removeView(mCameraPreview);
mCamera = null;
// release the camera for other applicationsCODE_IMG
}
}
catch(Exception e)
{}
}
#Override
public void onBackPressed() {
imgarrayList.clear();
intent.putCharSequenceArrayListExtra("List",imgarrayList);
setResult(RESULT_IMG,intent);
finish();
}
void cancleImg()
{}
public void deleteTempImg(Uri uri)
{
try {
File file = new File(uri.getPath());
boolean isdeleted = file.delete();
if(file.exists()){
boolean deleted = file.getCanonicalFile().delete();
if(deleted)
{Log.d("tag", "file deleted.");}
}
if(file.exists()){
this.getApplicationContext().deleteFile(file.getName());
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onResume() {
super.onResume();
try{
if (mCamera == null)
{
mCamera = getCameraInstance();
// three new lines, creating a new CameraPreview, then adding it to the FrameLayout
mCameraPreview = new CameraPreview(this, mCamera);
preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
}
}catch(Exception e)
{
e.printStackTrace();
}
}
/**
* Helper method to access the camera returns null if it cannot get the
* camera or does not exist
*
* #return
*/
private Camera getCameraInstance() {
mCamera = null;
try {
mCamera = Camera.open();
//STEP #1: Get rotation degrees
// Camera.CameraInfo info = new Camera.CameraInfo();
// Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, info);
// int rotation = this.getWindowManager().getDefaultDisplay().getRotation();
// int degrees = 0;
// switch (rotation) {
// case Surface.ROTATION_0: degrees = 0; break; //Natural orientation
// case Surface.ROTATION_90: degrees = 90; break; //Landscape left
// case Surface.ROTATION_180: degrees = 180; break;//Upside down
// case Surface.ROTATION_270: degrees = 270; break;//Landscape right
// }
// int rotate = (info.orientation - degrees + 360) % 360;
//STEP #2: Set the 'rotation' parameter
Camera.Parameters params = mCamera.getParameters();
// params.setRotation(rotate);
/* Set Auto focus */
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
// set the focus mode
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
// set Camera parameters
}
else{
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE))
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
mCamera.setParameters(params);
} catch (Exception e) {
// cannot get camera or does not exist
}
return mCamera;
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
public static Bitmap rotate(Bitmap bitmap, int degree) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
// mtx.postRotate(degree);
mtx.setRotate(degree);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}
#Override
protected void onStop() {
super.onStop();
}
}
CameraPreview.java
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
private LayoutInflater controlInflater = null;
// Constructor that obtains context and camera
#SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
#SuppressWarnings("deprecation")
Camera.Parameters parameters = mCamera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
parameters.set("orientation", "portrait");
mCamera.setDisplayOrientation(90);
parameters.setRotation(90);
}
else {
// This is an undocumented although widely known feature
parameters.set("orientation", "landscape");
// For Android 2.2 and above
mCamera.setDisplayOrientation(0);
// Uncomment for Android 2.0 and above
parameters.setRotation(0);
}
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
}
}
#SuppressWarnings("deprecation")
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
try{
surfaceHolder.removeCallback(this);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}catch(Exception e)
{
if(e!=null)
e.printStackTrace();}
}
#SuppressWarnings("deprecation")
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}

The right way to load a PDF into an ImageView

I'm looking for the proper way to load a PDF File into an ImageView.
I use the BitmapWorkerTask class from Android.
I have a button which allow me to choose the File I want to upload into the ImageView. When I click on this file, the process begin.
My issue is that my PDF is perfectly load 3 time 5. And I don't understand why it's not working the other time.
ImageView map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = (ImageView)findViewById(R.id.pdf);
}
/**
* Use this to load a pdf file from your assets and render it to a Bitmap.
*
* #param context
* current context.
* #param filePath
* of the pdf file in the assets.
* #return a bitmap.
*/
#Nullable
public static Bitmap renderToBitmap(Context context, String filePath) {
Bitmap bi = null;
InputStream inStream = null;
try {
inStream = new FileInputStream(filePath);
bi = renderToBitmap(context, inStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inStream.close();
} catch (IOException e) {
// do nothing because the stream has already been closed
}
}
return bi;
}
/**
* Use this to render a pdf file given as InputStream to a Bitmap.
*
* #param context
* current context.
* #param inStream
* the inputStream of the pdf file.
* #return a bitmap.
* #see https://github.com/jblough/Android-Pdf-Viewer-Library/
*/
#Nullable
public static Bitmap renderToBitmap(Context context, InputStream inStream) {
Bitmap bi = null;
try {
byte[] decode = IOUtils.toByteArray(inStream);
ByteBuffer buf = ByteBuffer.wrap(decode);
PDFPage mPdfPage = new PDFFile(buf).getPage(0);
float width = mPdfPage.getWidth();
float height = mPdfPage.getHeight();
RectF clip = null;
bi = mPdfPage.getImage((int) (width), (int) (height), clip, true,
true);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inStream.close();
} catch (IOException e) {
// do nothing because the stream has already been closed
}
}
return bi;
}
private void renderMap() {
String mapFilePath = Environment.getExternalStorageDirectory().toString()+"/Android/data/com.empower.data/"+mapFileName;
BitmapWorkerTask task = new BitmapWorkerTask(map, mapFilePath, MainActivity.this);
task.loadBitmap(R.id.pdf, map, mapFilePath);
map.setVisibility(View.VISIBLE);
map.invalidate();
}
And my BitmapWorkerTask.java
public class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private int data = 0;
private String mapFilePath1;
private Context context;
private RelativeLayout loadingPanel;
public BitmapWorkerTask(ImageView imageView, String mapFilePath2, Context context) {
// Use a WeakReference to ensure the ImageView can be garbage collected
this.context = context;
mapFilePath1 = mapFilePath2;
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
#Override
protected Bitmap doInBackground(Integer... params) {
data = params[0];
Bitmap bm = MainActivity.renderToBitmap(context , mapFilePath1);
return bm;
}
#Override
protected void onPreExecute() {
loadingPanel = (RelativeLayout)((Activity) context).findViewById(R.id.loadingPanel);
loadingPanel.setVisibility(View.VISIBLE);
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(final Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
loadingPanel.setVisibility(View.GONE);
}
}, 500);
}
}
}
public void loadBitmap(int resId, ImageView imageView, String mapFilePath1) {
BitmapWorkerTask task = new BitmapWorkerTask(imageView, mapFilePath1, context);
task.execute(resId);
}
}

aysnctask download all the images to the same item in the listview

I'm using asynctask to download image to listview with custom cursoradapter. The images are downloaded to the first item in the list and when I scroll down to the second and so on. It's not synchronize and it's not the right picture. What am I doing wrong?
I cant upload pictures so here is my code:
class DownloadItemdPoster extends AsyncTask {
#Override
protected Bitmap doInBackground(String... params) {
// get the address from the params:
String address = params[0];
HttpURLConnection connection = null;
InputStream stream = null;
ByteArrayOutputStream outputStream = null;
// the bitmap will go here:
Bitmap b = null;
try {
// build the URL:
URL url = new URL(address);
// open a connection:
connection = (HttpURLConnection) url.openConnection();
// check the connection response code:
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
// not good..
return null;
}
// the input stream:
stream = connection.getInputStream();
// get the length:
int length = connection.getContentLength();
// tell the progress dialog the length:
// this CAN (!!) be modified outside the UI thread !!!
// progressDialog.setMax(length);
// a stream to hold the read bytes.
// (like the StringBuilder we used before)
outputStream = new ByteArrayOutputStream();
// a byte buffer for reading the stream in 1024 bytes chunks:
byte[] buffer = new byte[1024];
int totalBytesRead = 0;
int bytesRead = 0;
// read the bytes from the stream
while ((bytesRead = stream.read(buffer, 0, buffer.length)) != -1) {
totalBytesRead += bytesRead;
outputStream.write(buffer, 0, bytesRead);
// notify the UI thread on the progress so far:
// publishProgress(totalBytesRead);
Log.d("TAG", "progress: " + totalBytesRead + " / " + length);
}
// flush the output stream - write all the pending bytes in its
// internal buffer.
outputStream.flush();
// get a byte array out of the outputStream
// theses are the bitmap bytes
byte[] imageBytes = outputStream.toByteArray();
// use the BitmapFactory to convert it to a bitmap
b = BitmapFactory.decodeByteArray(imageBytes, 0, length);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
// close connection:
connection.disconnect();
}
if (outputStream != null) {
try {
// close output stream:
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return b;
}
#Override
protected void onPostExecute(Bitmap result) {
ImageView itemPoster = (ImageView) findViewById(R.id.imageViewItemPoster);
if (result == null) {
// no image loaded - display the default image
itemPoster.setBackgroundResource(R.drawable.defaultitembackground);
Toast.makeText(MainActivity.this, "Error Loading Image",
Toast.LENGTH_LONG).show();
} else {
// set the showactivitybackground to the poster:
itemPoster.setImageBitmap(result);
}
};
}
public class MovieAdapter extends CursorAdapter {
public MovieAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return getLayoutInflater().inflate(R.layout.movies_item_layout,
parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
String movieName = cursor.getString(cursor
.getColumnIndex(DbConstants.MOVIE_NAME));
String movieGenre = cursor.getString(cursor
.getColumnIndex(DbConstants.MOVIE_GENRE));
String itemPoster = cursor.getString(cursor
.getColumnIndexOrThrow(DbConstants.MOVIE_POSTER));
String movieRuntime = cursor.getString(cursor
.getColumnIndex(DbConstants.MOVIE_RUNTIME));
String movieRating = cursor.getString(cursor
.getColumnIndex(DbConstants.MOVIE_RATING));
String movieReleasedYear = cursor.getString(cursor
.getColumnIndex(DbConstants.MOVIE_YEAR_RELEASD));
TextView name = (TextView) view
.findViewById(R.id.textViewMovieName);
TextView genre = (TextView) view
.findViewById(R.id.textViewMovieGenre);
TextView runtime = (TextView) view
.findViewById(R.id.textViewMovieRuntime);
TextView rating = (TextView) view
.findViewById(R.id.textViewMovieRating);
TextView year = (TextView) view
.findViewById(R.id.textViewMovieYear);
ImageView setItemPoster = (ImageView) view
.findViewById(R.id.imageViewItemPoster);
setItemPoster.setTag(1);
name.setText(movieName);
genre.setText("*" + movieGenre);
runtime.setText("*" + movieRuntime);
rating.setText("*" + "R:" + " " + movieRating);
year.setText("*" + movieReleasedYear);
if (setItemPoster != null) {
new DownloadItemdPoster().execute(itemPoster);
adapter.notifyDataSetChanged();
}
You can use Glide library to load image from server.Example :
Glide.with(mContext).load(url).into(myImageView);
You must have to use image loader lib(picasso , volley , universal loader lib) rather than make aysntask to load image from server.
UniversalLoaderLib
Example:-
Initiate below code in your adapter or activity once.
DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.loading_icon).showImageForEmptyUri(R.drawable.ic_error_transparent).showImageOnFail(R.drawable.ic_error_transparent)
.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565)/*.considerExifParams(true)*/.build();
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(activity.getBaseContext()));
Use below code where you want to load image from server.
ImageLoader.getInstance().displayImage(urladdress, imageview, options);

How to Store Image in SDCard using Service?

I am getting the Image URL and set that URL in GridView.it shows me Successfully in Gridview.But I also want to Store That Images in SDCard Using Service.How to do That.Please Someone Help me for my this Issue.Thank You.
public class MainActivity extends Activity {
ListView list;
GridView gv;
String TAG = "GRIDVIEW";
LazyAdapter adapter;
Bitmap bitmap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyService.class));
new loading().execute();
// gv = (GridView) findViewById(R.id.grid_view);
// startService(new Intent(MainActivity.this, MyService.class));
// gv = (GridView) findViewById(R.id.grid_view);
// gv.setAdapter(new LazyAdapter(MainActivity.this, mStrings));
// gv.setHorizontalSpacing(10);
// gv.setVerticalSpacing(40);
// gv.setGravity(200);
}
ProgressDialog mprogress;
private class loading extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
mprogress = new ProgressDialog(MainActivity.this);
mprogress.setMessage("Loading...");
mprogress.show();
super.onPreExecute();
}
protected String doInBackground(String... params) {
// startService(new Intent(MainActivity.this, MyService.class));
return null;
}
protected void onPostExecute(String result) {
getGirdview();
mprogress.dismiss();
super.onPostExecute(result);
}
private void getGirdview() {
gv = (GridView) findViewById(R.id.grid_view);
gv.setAdapter(new LazyAdapter(MainActivity.this, mStrings));
gv.setHorizontalSpacing(10);
gv.setVerticalSpacing(40);
}
}
public String[] mStrings = {
"http://a1.twimg.com/profile_images/97470808/icon_normal.png",
"http://a3.twimg.com/profile_images/511790713/AG.png",
};
}
public class MyService extends Service {
String TAG = "GRIDVIEW";
Bitmap bitmap;
MainActivity mclass = new MainActivity();
public void onStart(Intent intent, int startId) {
for (int i = 0; i < mclass.mStrings.length; i++) {
String str = mclass.mStrings[i];
bitmap = DownloadImage(str);
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
// R.drawable.ic_launcher);
// File sd = Environment.getExternalStorageDirectory();
File storagePath = new File(
Environment.getExternalStorageDirectory(), "Wallpaper");
storagePath.mkdirs();
String fileName = "test" + i + ".png";
File dest = new File(storagePath, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
super.onStart(intent, startId);
}
public int onStartCommand(Intent intent, int flags, int startId) {
// for (int i = 0; i < mStrings.length; i++) {
//
// String str = mStrings[i];
// bitmap = DownloadImage(str);
// // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
// // R.drawable.ic_launcher);
// // File sd = Environment.getExternalStorageDirectory();
// File storagePath = new File(
// Environment.getExternalStorageDirectory(), "Wallpaper");
// storagePath.mkdirs();
//
// String fileName = "test" + i + ".png";
// File dest = new File(storagePath, fileName);
// try {
// FileOutputStream out;
// out = new FileOutputStream(dest);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
// out.flush();
// out.close();
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
return super.onStartCommand(intent, flags, startId);
}
public IBinder onBind(Intent intent) {
return null;
}
// public void onStart(Intent intent, int startId) {
//
// for (int i = 0; i < mStrings.length; i++) {
//
// String str = mStrings[i];
// bitmap = DownloadImage(str);
// // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
// // R.drawable.ic_launcher);
// // File sd = Environment.getExternalStorageDirectory();
// File storagePath = new File(
// Environment.getExternalStorageDirectory(), "Wallpaper");
// storagePath.mkdirs();
//
// String fileName = "test" + i + ".png";
// File dest = new File(storagePath, fileName);
// try {
// FileOutputStream out;
// out = new FileOutputStream(dest);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
// out.flush();
// out.close();
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// super.onStart(intent, startId);
// }
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Toast.makeText(MyService.this, "Image is Downloaded",
Toast.LENGTH_SHORT).show();
return bitmap;
}
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.ic_launcher;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
Activity a = (Activity) photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
public class LazyAdapter extends BaseAdapter {
private Context mContext;
String TAG = "GridView";
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
Bitmap bitmap;
public LazyAdapter(Activity a, String[] d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return data;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.item, null);
}
// TextView txt_name = (TextView) convertView.findViewById(R.id.text);
// txt_name.setText("item" + position);
ImageView image = (ImageView) convertView.findViewById(R.id.image);
// image.setTag(data[position]);
imageLoader.DisplayImage(data[position], image);
return convertView;
}
}
Environment.getExternalStorage() will return the sd card location. Once you get the location, you can create directories as needed. Looks like you are doing it....so what is the issue that you are running into?
Also, use IntentService rather than a service......it takes care of most of the plumbing work for you.

Categories

Resources