Android - HTML ImageParser align center - android

I want to create a News App and now, my app displays posts from Json with Html Parser.
Images from HTML content was display with an ImageParser but was not align center. I need help to do this.
This is my code:
Spanned spanned = Html.fromHtml(json_data.getString("contenu"), this, null);
description_projet.setText(spanned);
#Override
public Drawable getDrawable(String source) {
LevelListDrawable d = new LevelListDrawable();
Drawable empty = getResources().getDrawable(R.drawable.ic_launcher);
d.addLevel(0, 0, empty);
d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
new LoadImage().execute(source, d);
return d;
}
class LoadImage extends AsyncTask<Object, Void, Bitmap> {
private LevelListDrawable mDrawable;
#Override
protected Bitmap doInBackground(Object... params) {
String source = (String) params[0];
mDrawable = (LevelListDrawable) params[1];
Log.d(TAG, "doInBackground " + source);
try {
InputStream is = new URL(source).openStream();
return BitmapFactory.decodeStream(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
Log.d(TAG, "onPostExecute drawable " + mDrawable);
Log.d(TAG, "onPostExecute bitmap " + bitmap);
if (bitmap != null) {
BitmapDrawable d = new BitmapDrawable(bitmap);
mDrawable.addLevel(1, 1, d);
mDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
mDrawable.setLevel(1);
CharSequence t = description_projet.getText();
description_projet.setText(t);
}
}
}
Thanks

Html.fromHtml() will create ImageSpans so you can just apply AlignmentSpans at the same points in the result:
#NonNull
public static Spanned centerImageSpans(#NonNull Spanned sp) {
ImageSpan[] imageSpans = sp.getSpans(0, sp.length(), ImageSpan.class);
if (imageSpans == null || imageSpans.length == 0) {
return sp;
}
SpannableString result = new SpannableString(sp);
for (ImageSpan imageSpan : imageSpans) {
AlignmentSpan alignSpan = new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER);
int start = result.getSpanStart(imageSpan);
int end = result.getSpanEnd(imageSpan);
result.setSpan(alignSpan, start, end, 0);
}
return result;
}

Related

How to apply bitmap recycle in recycleView because of out of memory exception

I am working with an application and have about 10 Recycle view, when i move between fragments, app crash with out of memory.
I am using a lot of images in this app
I want to know how to apply bitmap recycle as it's the main reason of the exception
My recycle adapter is:
public void onBindViewHolder(MboViewHolder holder, int position) {
GameEvent gameEvent = ev.get(position);
holder.bindPhoto(holder,cnt,gameEvent.getEventImage());}
BindPhoto mwthod is:
public void bindPhoto(MboViewHolder mbo,Context cnt, String photoUrl) {
mbo.img.setTag(photoUrl);
Bitmap imgz = Tools.getPhoto(photoUrl, 0);
if (imgz != null) {
mbo.img.setImageBitmap(imgz);
Log.e("NoDwnLd","No");
} else {
Bitmap largeIcon = BitmapFactory.decodeResource(cnt.getResources(), R.drawable.ic_default);
mbo.img.setImageBitmap(largeIcon);
new DownloadBitmap(cnt,mbo.img,"2").execute(photoUrl);
}
My DownloadBitmap asynctask is:
public class DownloadBitmap extends AsyncTask<String, Void, Bitmap> {
private int flag=0;
private ImageView img;
private String type;
private HashMap<String, Bitmap> map= new HashMap<>();
private Context cnt;
private String url;
public DownloadBitmap(Context cnt, ImageView img, String type) {
this.cnt = cnt;
this.img=img;
this.type=type;
}
public DownloadBitmap(Context cnt, ImageView img, String type, HashMap<String, Bitmap> map) {
this.cnt = cnt;
this.img=img;
this.type=type;
this.map=map;
}
public DownloadBitmap(Context context) {
this.cnt=context;
this.flag=2;
}
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap=null;
if (cnt!=null){
boolean check = new CheckInternetConnection(cnt).haveNetworkConnection();
if (check) {
try {
url=params[0];
if (url==null || url.equals("")) return null;
InputStream in = new java.net.URL(url).openStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = Globals.inSampleSize;
bitmap = BitmapFactory.decodeStream(in,null,options);
return bitmap;
} catch (Exception e) {
Log.e("ImageDownload", "Download failed: " + e.getMessage());
}
}
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if(bitmap != null){
bitmap=Tools.resizeImage(bitmap,500,500);
//view.setImageViewBitmap(R.id.nt_img, bitmap);
if(type == "1") Tools.sendNotification(cnt, bitmap);
if(type == "2") {
if(img.getTag()!= null && img.getTag() == url){
// keep all images stored on memory for fast retrieval
// map.put(url, bitmap);
// Log.e("url", url);
// save the image inside the image holder
//img.setImageBitmap(map.get(url));
Log.e("DwnLD",img.getTag()+"");
img.setImageBitmap(bitmap);
Tools.storePhoto(img.getTag().toString(), bitmap);
}
// Log.e("ImageDownload", "bitmap in imageview");
}
if (type == null){
// map.put(url, bitmap);
// if (img!=null && map.get(url)!=null)img.setImageBitmap(map.get(url));
if (img!=null)img.setImageBitmap(bitmap);
}
if (cnt != null && flag ==2){
Tools.storePhoto(CreateEvent1Fragment.searchResult.get(0).getEventImage(),bitmap);
// Log.e("ImageDownload", "bitmap in imageview");
}
}
}
My Tools.resizeImage is:
public static Bitmap resizeImage(Bitmap bitmap,int newWidth,int newHeight){
Bitmap resized = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
return resized;
}
My Tools.storePhoto is:
public static void storePhoto(String url,Bitmap image){
File img = null;
File env = new File(Environment.getExternalStorageDirectory() + Globals.DIR);
if(!env.exists()) env.mkdir();
String filename = extractUrl(url);
img=new File(Environment.getExternalStorageDirectory()+Globals.DIR+filename);
if (!img.exists()) {
// Log.e("PHOTOS",img.getAbsolutePath());
try {
FileOutputStream fos = new FileOutputStream(img);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
My Tools.getPhoto is:
public static Bitmap getPhoto(String url,int type){
Bitmap bmp=null;
String filename = extractUrl(url);
File ff = new File(Environment.getExternalStorageDirectory()+Globals.DIR+filename);
if(!ff.exists()){
return bmp;
}else {
if (type != 1){
bmp = Tools.decodeFile(ff);
return bmp;
}else {
bmp = BitmapFactory.decodeFile(ff.getAbsolutePath());
return bmp;
}
}
}
My Tools.decodeFile is:
public static Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE=70;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while(o.outWidth / scale / 2 >= REQUIRED_SIZE &&
o.outHeight / scale / 2 >= REQUIRED_SIZE) {
scale *= 2;
}
o.inSampleSize = scale;
o.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o);
} catch (FileNotFoundException e) {}
return null;
}
I want to apply bitmap recycle... How can I do that?
try using Libs Glide
https://github.com/bumptech/glide
change
if (imgz != null) {
mbo.img.setImageBitmap(imgz);
Log.e("NoDwnLd","No");
} else {
Bitmap largeIcon = BitmapFactory.decodeResource(cnt.getResources(), R.drawable.ic_default);
mbo.img.setImageBitmap(largeIcon);
new DownloadBitmap(cnt,mbo.img,"2").execute(photoUrl);
}
to
if(!photoUrl.isEmpty()) {
Glide.with(this).load(photoUrl).error(R.drawable.ic_default).into(mbo.img);
Log.e("NoDwnLd","No");
} else {
Glide.with(this).load(R.drawable.ic_default).error(R.drawable.ic_default).into(mbo.img);
new DownloadBitmap(cnt,mbo.img,"2").execute(photoUrl);
}

How to reload images, if any exception ocurrs using imageGetter

I'm trying to parse images that comes in <img> tag using ImageGetter. I'm successfully able to parse and download the images. But,in worst cases, like no coonectivity, low network, if the image is not loaded, I want to reload the image. As per my understanding , I reload the image in onPostExecute() method of Asynctask when bitmap is null. But for this, Again I have to call the Asynctask method. Is there any other alternative to reload the image.
Below is my Imagegetter Code:
public class UrlImageParser implements Html.ImageGetter {
private static String TAG = "ImageParser";
private TextView mContainer;
private Context mContext;
Point outSize=new Point();
float destWidth=1;
float destHeight=1;
public UrlImageParser(TextView t, Context context) {
mContainer = t;
mContext = context;
}
#Override
public Drawable getDrawable(String source) {
LevelListDrawable d = new LevelListDrawable();
Drawable empty = mContext.getResources().getDrawable(R.drawable.story_img_placeholder);
d.addLevel(0, 0, empty);
d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
new LoadImage().execute(source, d);
return d;
}
class LoadImage extends AsyncTask<Object, Void, Bitmap> {
private LevelListDrawable mDrawable;
#Override
protected Bitmap doInBackground(Object... params) {
String source = (String) params[0];
mDrawable = (LevelListDrawable) params[1];
Log.d(TAG, "doInBackground " + source);
try {
InputStream is = new URL(source).openStream();
return BitmapFactory.decodeStream(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
Log.d(TAG, "onPostExecute drawable " + mDrawable);
Log.d(TAG, "onPostExecute bitmap " + bitmap);
if (bitmap != null) {
BitmapDrawable d = new BitmapDrawable(scaleBitmap(bitmap));
mDrawable.addLevel(1, 1, d);
/*int width = bitmap.getWidth();
int screenWidth = Utility.getScreenWidth(mContext);
int height = (int) (screenWidth * 0.62);*/
mDrawable.setBounds(0, 0, d.getBitmap().getWidth(), d.getBitmap().getHeight());
mDrawable.setLevel(1);
/*// redraw the image by invalidating the container
UrlImageParser.this.container.invalidate(); */
if (mContainer != null) {
mContainer.setText(mContainer.getText());
}
}else{
//Some error occured, send the request again
}
}
}
private Bitmap scaleBitmap(Bitmap mFile){
Display display = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if (android.os.Build.VERSION.SDK_INT >= 13){
display.getSize(outSize);
destWidth = outSize.x;
destHeight = outSize.y;
}else{
destWidth=display.getWidth();
destHeight=display.getHeight();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap orig = mFile;
float srcWidth = orig.getWidth();
float srcHeight = orig.getHeight();
Bitmap resized=Bitmap.createScaledBitmap(orig, (int)Math.round(destWidth), (int)Math.round(destWidth * srcHeight /srcWidth), true);
destWidth=1;
destHeight=1;
return resized;
}
}
The best way to do this is to never leave doInBackground() or to start the entire AsyncTask again. You could do something like this:
int failureCounter = 0;
#Override
protected Bitmap doInBackground(Object... params) {
try {
String source = (String) params[0];
mDrawable = (LevelListDrawable) params[1];
Log.d(TAG, "doInBackground " + source);
InputStream is = new URL(source).openStream();
return BitmapFactory.decodeStream(is);
} catch (Exception e) {
e.printStackTrace();
if(this.failureCounter++ >= 5) {
return null;
} else {
return this.doInBackground(params);
}
}
}
This code snippet will retry to load the image 5 times before it returns null. You should limit the number of tries to prevent a StackOverflowError and to limit the time your task is running as AsyncTasks are not ment to be a long-running background task.

Accessing Full Frame Using ZXing on Android

We are developing an Android application and using ZXing for scanning QR codes. Is there a way to get full frame of decoded QR code using ZXing ?
Following method is added to PlanarYUVLuminanceSource class.
public void saveFrame() {
try {
YuvImage image = new YuvImage(yuvData, ImageFormat.NV21, getWidth(), getHeight(), null);
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/frame.jpeg");
FileOutputStream fos = new FileOutputStream(file);
image.compressToJpeg(new Rect(0, 0, image.getWidth(), image.getHeight()), 100, fos);
} catch (FileNotFoundException e) {
Log.e(TAG, "FileNotFoundException!");
}
}
Called within DecodeHandler class as below,
private void decode(byte[] data, int width, int height) {
long start = System.currentTimeMillis();
Result rawResult = null;
PlanarYUVLuminanceSource source = CameraManager.get()
.buildLuminanceSource(data, width, height);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = multiFormatReader.decodeWithState(bitmap);
} catch (ReaderException re) {
// continue
} finally {
multiFormatReader.reset();
}
if (rawResult != null) {
// Don't log the barcode contents for security.
long end = System.currentTimeMillis();
Log.d(TAG, "Found barcode in " + (end - start) + " ms");
Message message = Message.obtain(activity.getHandler(),
R.id.zxinglib_decode_succeeded, rawResult);
Bundle bundle = new Bundle();
bundle.putParcelable(DecodeThread.BARCODE_BITMAP,
source.renderCroppedGreyscaleBitmap());
source.saveFrame();
message.setData(bundle);
message.sendToTarget();
} else {
Message message = Message.obtain(activity.getHandler(),
R.id.zxinglib_decode_failed);
message.sendToTarget();
}
}
Here is result image,
Finally I found a solution. It is based on renderCroppedGreyscaleBitmap() method of PlanarYUVLuminanceSource class. Here is how I changed decode() method.
private void decode(byte[] data, int width, int height) {
long start = System.currentTimeMillis();
Result rawResult = null;
PlanarYUVLuminanceSource source = CameraManager.get().buildLuminanceSource(data, width, height);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = multiFormatReader.decodeWithState(bitmap);
} catch (ReaderException re) {
// continue
} finally {
multiFormatReader.reset();
}
if (rawResult != null) {
// Don't log the barcode contents for security.
long end = System.currentTimeMillis();
Log.d(TAG, "Found barcode in " + (end - start) + " ms");
// Grab & save frame
Bitmap wholeBmp = renderGrayScaleBitmap(data, width, height);
if(wholeBmp != null)
saveBitmap(wholeBmp, "frame.png");
else
Log.e(TAG, "Bitmap of frame is empty!");
Message message = Message.obtain(activity.getHandler(), R.id.zxinglib_decode_succeeded, rawResult);
Bundle bundle = new Bundle();
bundle.putParcelable(DecodeThread.BARCODE_BITMAP, source.renderCroppedGreyscaleBitmap());
message.setData(bundle);
message.sendToTarget();
} else {
Message message = Message.obtain(activity.getHandler(), R.id.zxinglib_decode_failed);
message.sendToTarget();
}
}
Create bitmap from decode data
private Bitmap renderGrayScaleBitmap(byte[] data, int width, int height) {
int[] pixels = new int[width * height];
int inputOffset = width;
for (int y = 0; y < height; y++) {
int outputOffset = y * width;
for (int x = 0; x < width; x++) {
int grey = data[inputOffset + x] & 0xff;
pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101);
}
inputOffset += width;
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
Save bitmap to sdcard
private void saveBitmap(Bitmap bmp, String name) {
FileOutputStream out = null;
try {
String filename = Environment.getExternalStorageDirectory().toString() + "/" + name;
Log.i(TAG, "writtenPath=" + filename);
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

current activity taking screenshot and save image into sdcard in android

Hi In my application I am making an application in android in which I have to take screenshot of current activity and save it into sdcard.
For that i used one menu button named as download if i click the download i want to save the current activity into sdcard.
Now My problem is it's saving into sdcard but screenshot coming half.I want to download the whole screen and save it into sdcard.how to download the full activity.
Can anyone please help me how to solve this problem.
notify_image
public class notify_image extends Activity {
ImageView imageView;
Activity av=notify_image.this;
Bitmap b;
String strFileName;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notify_image);
imageView = (ImageView) findViewById(R.id.iv_imageview);
Intent in = getIntent();
String title = in.getStringExtra("TAG_TITLE");
String url = in.getStringExtra("TAG_URL");
String name = in.getStringExtra("TAG_NAME");
String place = in.getStringExtra("TAG_PLACE");
String date = in.getStringExtra("TAG_DATE");
final String URL =url;
TextView stitle = (TextView) findViewById(R.id.tv_title);
TextView sname = (TextView) findViewById(R.id.tv_name);
TextView splace = (TextView) findViewById(R.id.tv_place);
TextView sdate = (TextView) findViewById(R.id.tv_date);
// displaying selected product name
stitle.setText(title);
sname.setText(name);
splace.setText(place);
sdate.setText(date);
// Create an object for subclass of AsyncTask
GetXMLTask task = new GetXMLTask();
// Execute the task
task.execute(new String[] { URL });
}
//creating button
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.downloads, menu);
return true;
}
//button on click function
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.downloads:
/*Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
*/
//captureScreen(v);
try{
Bitmap bitmap = takeScreenShot(av); // av is instance of hello
savePic(bitmap, strFileName);
}
catch (Exception e) {
System.out.println(e);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay()
.getHeight();
// Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return b;
}
/*public void takeScreen() {
Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
fout.close();
}
}*/
#SuppressWarnings("unused")
private static void savePic(Bitmap bitmap, String strFileName) {
//File strFileName1 = new File(Environment.getExternalStorageDirectory() + "/screenshottt.png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream("mnt/sdcard/print.png");
if (null != fos) {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
System.out.println("b is:"+bitmap);
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void shoot(Activity a,String b) {
//savePic(takeScreenShot(a), "sdcard/xx.png");
savePic(takeScreenShot(a), b);
}
/*public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}*/
/*public Bitmap captureScreen(View v)
{
Bitmap bitmap = null;
try {
if(v!=null)
{
int width = v.getWidth();
int height = v.getHeight();
Bitmap screenshot = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
v.draw(new Canvas(screenshot));
}
} catch (Exception e)
{
Log.d("captureScreen", "Failed");
}
return bitmap;
}
*/
/* public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}*/
/* public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}*/
//image url convert to bitmap
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
}
Thanks In Advance.
new updated code
public class notify_image extends Activity {
ImageView imageView;
Activity av=notify_image.this;
Bitmap b;
String strFileName;
Button download;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notify_image);
imageView = (ImageView) findViewById(R.id.iv_imageview);
download = (Button) findViewById(R.id.button1);
download();
Intent in = getIntent();
String title = in.getStringExtra("TAG_TITLE");
String url = in.getStringExtra("TAG_URL");
String name = in.getStringExtra("TAG_NAME");
String place = in.getStringExtra("TAG_PLACE");
String date = in.getStringExtra("TAG_DATE");
final String URL =url;
TextView stitle = (TextView) findViewById(R.id.tv_title);
TextView sname = (TextView) findViewById(R.id.tv_name);
TextView splace = (TextView) findViewById(R.id.tv_place);
TextView sdate = (TextView) findViewById(R.id.tv_date);
// displaying selected product name
stitle.setText(title);
sname.setText(name);
splace.setText(place);
sdate.setText(date);
// Create an object for subclass of AsyncTask
GetXMLTask task = new GetXMLTask();
// Execute the task
task.execute(new String[] { URL });
}
//creating button
/* public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.downloads, menu);
return true;
}
*/
//button on click function
/* public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.downloads:
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
//captureScreen(v);
try{
Bitmap bitmap = takeScreenShot(av); // av is instance of hello
savePic(bitmap, strFileName);
}
catch (Exception e) {
System.out.println(e);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}*/
private void download() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
/*Intent nextScreen = new Intent(getApplicationContext(), KnowYourLeader.class);
startActivity(nextScreen);*/
try{
Bitmap bitmap = takeScreenShot(av); // av is instance of hello
savePic(bitmap, strFileName);
}
catch (Exception e) {
System.out.println(e);
}
}
private static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay()
.getHeight();
// Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return b;
}
/*public void takeScreen() {
Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
fout.close();
}
}*/
#SuppressWarnings("unused")
private static void savePic(Bitmap bitmap, String strFileName) {
//File strFileName1 = new File(Environment.getExternalStorageDirectory() + "/screenshottt.png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream("mnt/sdcard/print.png");
if (null != fos) {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
System.out.println("b is:"+bitmap);
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void shoot(Activity a,String b) {
//savePic(takeScreenShot(a), "sdcard/xx.png");
savePic(takeScreenShot(a), b);
}
/*public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}*/
/*public Bitmap captureScreen(View v)
{
Bitmap bitmap = null;
try {
if(v!=null)
{
int width = v.getWidth();
int height = v.getHeight();
Bitmap screenshot = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
v.draw(new Canvas(screenshot));
}
} catch (Exception e)
{
Log.d("captureScreen", "Failed");
}
return bitmap;
}
*/
/* public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}*/
/* public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}*/
//image url convert to bitmap
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
}
Here is the code that allowed my screen shot to be stored on sd card and used later for whatever your needs are, you can achieve it with following code:
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;
// create bitmap screen capture
Bitmap bitmap;
View v1 = view.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
imageFile = new File(mPath);
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Then, when you need to access use something like this:
Uri uri = Uri.fromFile(new File(mPath));
Try out below code to capture the whole screen and save as bitmap.:
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, "print.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage( getContentResolver(), b,
"Screen", "screen");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope this will help you.

png downloaded size different to server size?

My app downloads .png files to the sd card for later use. I kept getting OutOfMemoryErrors (if anyone could explain this too, that'd be great!) and so I took a look at the sizes of the images saved to the sd card, and they seem to be roughly double what they are on the server. Why is this, and how can I make them smaller?
public void onCreate(Bundle saved) {
setContentView(R.layout.namedrxnscreen);
TextView t1 = (TextView)findViewById(R.id.rxn_text1);
TextView t2 = (TextView)findViewById(R.id.rxn_text2);
TextView t3 = (TextView)findViewById(R.id.rxn_text3);
TextView t4 = (TextView)findViewById(R.id.rxn_text4);
iv = (ImageView) findViewById(R.id.rxn_image);
pb = (ProgressBar) findViewById(R.id.rxn_loading);
vs = (ViewSwitcher) findViewById(R.id.rxn_switch);
try {
super.onCreate(saved);
[ boring stuff here ]
BitmapDrawable image = getImage(c.getString(5));
if (image != null) {
iv.setImageDrawable(getImage(c.getString(5)));
iv.setBackgroundColor(Color.WHITE);
vs.setDisplayedChild(1);
}
else {
new DownloadTask().execute(c.getString(5));
}
}
catch (ArrayIndexOutOfBoundsException ea) {
error = "bah!";
showDialog(1);
}
catch (Exception ex) {
error = ex.getMessage();
showDialog(1);
}
}
protected class DownloadTask extends AsyncTask<String, Integer, Bitmap> {
#Override
protected Bitmap doInBackground(String... string) {
Bitmap d = null;
try {
DefaultHttpClient dhc = new DefaultHttpClient();
HttpGet request = new HttpGet(HTTP_BASE + string[0] + ".png");
HttpResponse response = dhc.execute(request);
BufferedInputStream webstream = new BufferedInputStream(response.getEntity().getContent());
d = writeToSd(string[0], webstream, d);
}
catch (Exception ex) { errorCatch(ex.getMessage()); }
return d;
}
private Bitmap writeToSd(String string, BufferedInputStream webstream, Bitmap d) {
try {
webstream.mark(3);
webstream.reset();
File f = new File(Environment.getExternalStorageDirectory() + SD_DIR);
f.mkdirs();
File f2 = new File(f, string + ".png");
f2.createNewFile();
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(f2));
int len;
byte[] buffer = new byte[1024];
while ((len = webstream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
webstream.close();
//fos.flush();
fos.close();
FileInputStream fis = new FileInputStream(new File(f, string + ".png"));
d = BitmapFactory.decodeStream(fis);
return d;
}
catch (Exception ex) {
errorCatch(ex.getMessage());
return null;
}
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
iv.setImageBitmap(result);
iv.setBackgroundColor(Color.WHITE);
vs.setDisplayedChild(1);
}
}
}
protected BitmapDrawable getImage(String name) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
//Gets the SD card file, whacks it in a stream
File f = new File(Environment.getExternalStorageDirectory() + SD_DIR, name + ".png");
if (f.exists()) {
InputStream s = new FileInputStream(f);
try {
//Return the decoded bitmap
BitmapDrawable d = new BitmapDrawable(getResources(),
BitmapFactory.decodeStream(s)); //gives an OutOfMemoryError if png > ~30KB
return d;
} catch (OutOfMemoryError ex) {
Toast.makeText(this, "An OutOfMemoryError occured and" +
" the image was loaded at a lower quality.", Toast.LENGTH_SHORT).show();
BitmapFactory.Options mOptions = new BitmapFactory.Options();
mOptions.inSampleSize = 4;
BitmapDrawable d = new BitmapDrawable(getResources(),
BitmapFactory.decodeStream(s, null, mOptions));
return d;
}
}
else return null;
}
catch (Exception ex) {
return null;
}
}
else {
Toast.makeText(this, "External storage not available. Downloading from internet.",
Toast.LENGTH_SHORT).show();
return null;
}
}
The picture downloaded from the server is done byte per byte and cannot be double sized magically...

Categories

Resources