List of usage examples for android.graphics BitmapFactory decodeFile
public static Bitmap decodeFile(String pathName)
From source file:com.fada.sellsteward.myweibo.sina.net.Utility.java
public static String openUrl(Context context, String url, String method, WeiboParameters params, String file, Token token) throws WeiboException { String result = ""; try {/*from w w w . ja v a2s . c o m*/ HttpClient client = getNewHttpClient(context); HttpUriRequest request = null; ByteArrayOutputStream bos = null; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); HttpGet get = new HttpGet(url); request = get; } else if (method.equals("POST")) { HttpPost post = new HttpPost(url); byte[] data = null; bos = new ByteArrayOutputStream(1024 * 50); if (!TextUtils.isEmpty(file)) { Utility.paramToUpload(bos, params); post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); Bitmap bf = BitmapFactory.decodeFile(file); Utility.imageContentToUpload(bos, bf); } else { post.setHeader("Content-Type", "application/x-www-form-urlencoded"); String postParam = encodeParameters(params); data = postParam.getBytes("UTF-8"); bos.write(data); } data = bos.toByteArray(); bos.close(); // UrlEncodedFormEntity entity = getPostParamters(params); ByteArrayEntity formEntity = new ByteArrayEntity(data); post.setEntity(formEntity); request = post; } else if (method.equals("DELETE")) { request = new HttpDelete(url); } setHeader(method, request, params, url, token); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); int statusCode = status.getStatusCode(); if (statusCode != 200) { result = read(response); String err = null; int errCode = 0; try { JSONObject json = new JSONObject(result); err = json.getString("error"); errCode = json.getInt("error_code"); } catch (JSONException e) { e.printStackTrace(); } throw new WeiboException(String.format(err), errCode); } // parse content stream from response result = read(response); return result; } catch (IOException e) { throw new WeiboException(e); } }
From source file:com.joy.weibo.net.Utility.java
public static String openUrl(Context context, String url, String method, WeiboParameters params, String file, Token token) throws WeiboException { String result = ""; try {/*from w w w .j av a 2s . c o m*/ HttpClient client = getNewHttpClient(context); HttpUriRequest request = null; ByteArrayOutputStream bos = null; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); HttpGet get = new HttpGet(url); request = get; } else if (method.equals("POST")) { HttpPost post = new HttpPost(url); byte[] data = null; bos = new ByteArrayOutputStream(1024 * 50); if (!TextUtils.isEmpty(file)) { Utility.paramToUpload(bos, params); post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); Bitmap bf = BitmapFactory.decodeFile(file); Utility.imageContentToUpload(bos, bf); } else { post.setHeader("Content-Type", "application/x-www-form-urlencoded"); String postParam = encodeParameters(params); data = postParam.getBytes("UTF-8"); bos.write(data); } data = bos.toByteArray(); bos.close(); // UrlEncodedFormEntity entity = getPostParamters(params); ByteArrayEntity formEntity = new ByteArrayEntity(data); post.setEntity(formEntity); request = post; } else if (method.equals("DELETE")) { request = new HttpDelete(url); } setHeader(method, request, params, url, token); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); int statusCode = status.getStatusCode(); if (statusCode != 200) { result = read(response); String err = null; int errCode = 0; try { JSONObject json = new JSONObject(result); err = json.getString("error"); errCode = json.getInt("error_code"); System.out.println(errCode + "/" + err); } catch (JSONException e) { System.out.println(errCode + "/" + err); e.printStackTrace(); } throw new WeiboException(String.format(err), errCode); } // parse content stream from response result = read(response); return result; } catch (IOException e) { throw new WeiboException(e); } }
From source file:com.akop.bach.ImageCache.java
public Bitmap getBitmap(String imageUrl, CachePolicy cachePol) { if (imageUrl == null || imageUrl.length() < 1) return null; File file = getCacheFile(imageUrl, cachePol); // See if it's in the local cache // (but only if not being forced to refresh) if (!cachePol.bypassCache && file.canRead()) { if (App.getConfig().logToConsole()) App.logv("Cache hit: " + file.getName()); try {/*from w w w .j a v a 2 s . com*/ if (!cachePol.expired(System.currentTimeMillis(), file.lastModified())) return BitmapFactory.decodeFile(file.getAbsolutePath()); } catch (OutOfMemoryError e) { return null; } } // Fetch the image byte[] blob; int length; try { HttpClient client = new IgnorantHttpClient(); HttpParams params = client.getParams(); params.setParameter("http.useragent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;)"); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_MS); HttpConnectionParams.setSoTimeout(params, TIMEOUT_MS); HttpResponse resp = client.execute(new HttpGet(imageUrl)); HttpEntity entity = resp.getEntity(); if (entity == null) return null; InputStream stream = entity.getContent(); if (stream == null) return null; try { if ((length = (int) entity.getContentLength()) <= 0) { // Length is negative, perhaps content length is not set ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int chunkSize = 5000; byte[] chunk = new byte[chunkSize]; for (int r = 0; r >= 0; r = stream.read(chunk, 0, chunkSize)) byteStream.write(chunk, 0, r); blob = byteStream.toByteArray(); } else { // We know the length blob = new byte[length]; // Read the stream until nothing more to read for (int r = 0; r < length; r += stream.read(blob, r, length - r)) ; } } finally { stream.close(); entity.consumeContent(); } } catch (IOException e) { if (App.getConfig().logToConsole()) e.printStackTrace(); return null; } // if (file.canWrite()) { FileOutputStream fos = null; try { fos = new FileOutputStream(file); if (cachePol.resizeWidth > 0 || cachePol.resizeHeight > 0) { Bitmap bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length); float aspectRatio = (float) bmp.getWidth() / (float) bmp.getHeight(); int newWidth = (cachePol.resizeWidth <= 0) ? (int) ((float) cachePol.resizeHeight * aspectRatio) : cachePol.resizeWidth; int newHeight = (cachePol.resizeHeight <= 0) ? (int) ((float) cachePol.resizeWidth / aspectRatio) : cachePol.resizeHeight; Bitmap resized = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true); resized.compress(Bitmap.CompressFormat.PNG, 100, fos); return resized; } else { fos.write(blob); } if (App.getConfig().logToConsole()) App.logv("Wrote to cache: " + file.getName()); } catch (IOException e) { if (App.getConfig().logToConsole()) e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } } } Bitmap bmp = null; try { bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length); } catch (Exception e) { if (App.getConfig().logToConsole()) e.printStackTrace(); } return bmp; }
From source file:com.support.android.designlibdemo.activities.CampaignDetailActivity.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == TAKE_PHOTO_CODE) { photoBitmap = BitmapFactory.decodeFile(photoUri.getPath()); Bitmap resizedImage = BitmapScaler.scaleToFitWidth(photoBitmap, 300); ivCampaignImage.getAdjustViewBounds(); ivCampaignImage.setScaleType(ImageView.ScaleType.FIT_XY); //********** Update parse with image // Convert bitmap to a byte array ByteArrayOutputStream stream = new ByteArrayOutputStream(); resizedImage.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] image = stream.toByteArray(); // Create the ParseFile with an image final ParseFile file = new ParseFile( "posted_by_user_" + ParseUser.getCurrentUser().getUsername() + ".jpg", image); //posting an image file with campaign id to Parse to Images object ParseObject photoPost = new ParseObject("Images"); photoPost.put("imagePost", file); photoPost.put("campaignId", campaign.getObjectId()); photoPost.saveInBackground(new SaveCallback() { @Override//from ww w.jav a 2 s . c o m public void done(ParseException e) { getImagesUploadedByUserForCampaign(campaign.getObjectId()); } }); } else if (requestCode == PICK_PHOTO_CODE) { photoUri = data.getData(); try { photoBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri); } catch (IOException e) { e.printStackTrace(); } Bitmap resizedImage = BitmapScaler.scaleToFitWidth(photoBitmap, 300); ivCampaignImage.getAdjustViewBounds(); ivCampaignImage.setScaleType(ImageView.ScaleType.FIT_XY); //********** Update parse with image //ivCampaignImage.setImageBitmap(resizedImage); // Convert bitmap to a byte array ByteArrayOutputStream stream = new ByteArrayOutputStream(); resizedImage.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] image = stream.toByteArray(); // Create the ParseFile with an image final ParseFile file = new ParseFile( "posted_by_user_" + ParseUser.getCurrentUser().getUsername() + ".jpg", image); //posting an image file with campaign id to Parse to Images object ParseObject photoPost = new ParseObject("Images"); photoPost.put("imagePost", file); photoPost.put("campaignId", campaign.getObjectId()); photoPost.saveInBackground(); photoPost.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { getImagesUploadedByUserForCampaign(campaign.getObjectId()); } }); } else if (requestCode == CROP_PHOTO_CODE) { photoBitmap = data.getParcelableExtra("data"); ivCampaignImage.getAdjustViewBounds(); ivCampaignImage.setScaleType(ImageView.ScaleType.FIT_XY); ivCampaignImage.setImageBitmap(photoBitmap); Toast.makeText(this, "I just took a picture", Toast.LENGTH_LONG).show(); } } }
From source file:com.bravo.ecm.service.ScannedFile.java
public boolean loadCover(ConnectivityManager.WakeLock lock) { try {//from ww w . j ava 2s. c om if (getCover() != null) { if (getCover().startsWith("http")) { String name; if (m_BookId != null) { if (matchSubject("Fictionwise")) { if (pathname != null && !pathname.trim().equals("")) { name = (new File(pathname)).getName(); int idx = name.lastIndexOf('.'); if (idx == -1) { idx = name.length(); } name = name.substring(0, idx); } else { name = titles.get(0); } for (int i = 0; i < ReservedChars.length(); i++) { name = name.replace(ReservedChars.charAt(i), '_'); } name = FictionwiseBooks.getBaseDir() + name + ".jpg"; } else { int idx = m_DownloadUrl.lastIndexOf('/'); int idx1 = m_DownloadUrl.lastIndexOf('.'); name = m_DownloadUrl.substring(idx + 1, idx1); name = Smashwords.getBaseDir() + name + ".jpg"; } } else { if (pathname != null && !pathname.trim().equals("")) { name = (new File(pathname)).getName(); int idx = name.lastIndexOf('.'); name = name.substring(0, idx); } else { name = titles.get(0); } for (int i = 0; i < ReservedChars.length(); i++) { name = name.replace(ReservedChars.charAt(i), '_'); } name = "/system/media/sdcard/my B&N downloads/" + name + ".jpg"; } try { if ((new File(name)).exists()) { Bitmap myBitmap; try { myBitmap = BitmapFactory.decodeFile(name); } catch (Throwable err) { myBitmap = null; } if (myBitmap != null && myBitmap.getWidth() > 0) { setCover(name); m_NookLibrary.updateCover(this); return true; } } if (lock != null && !lock.isHeld()) { boolean ret = m_NookLibrary.waitForNetwork(lock); if (!ret) return false; } DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet request = new HttpGet(getCover()); HttpResponse response = httpClient.execute(request); String type = response.getEntity().getContentType().getValue(); if (type != null && (type.contains("htm") || type.contains("txt"))) { return false; } BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent(), 1024); FileOutputStream fout = new FileOutputStream(new File(name)); byte[] buffer = new byte[1024]; int len; while ((len = bis.read(buffer)) >= 0) { fout.write(buffer, 0, len); } bis.close(); fout.close(); setCover(name); m_NookLibrary.updateCover(this); return true; } catch (Exception ex) { Log.e("loadCover", ex.getMessage(), ex); File tmp = new File(name); tmp.delete(); ex.printStackTrace(); } } else { return true; } } String[] fileTypes = { ".jpg", ".jpeg", ".PNG", ".png", ".gif", ".JPG", ".JPEG", ".GIF" }; boolean found = false; String cover = ""; int idx; String path1; if (pathname != null && !pathname.trim().equals("")) { idx = pathname.lastIndexOf('.'); if (idx == -1) { path1 = pathname; } else { path1 = pathname.substring(0, idx); } } else { path1 = "/system/media/sdcard/my B&N downloads/" + titles.get(0); } int attempt = 1; while (!found && attempt < 4) { for (String s : fileTypes) { File f = new File(path1 + s); if (f.exists()) { cover = path1 + s; found = true; break; } } if (found) { setCover(cover); m_NookLibrary.updateCover(this); return found; } else if (attempt == 1) { attempt++; path1 = pathname.replace("/sdcard/", "/sdcard/Digital Editions/Thumbnails/"); } else if (attempt == 2) { path1 = pathname.replace("/sdcard/", "/system/media/sdcard/Digital Editions/Thumbnails/"); attempt++; } else { attempt++; } } if ("epub".equals(type)) { boolean ret = EpubMetaReader.loadCover(this); if (ret) { m_NookLibrary.updateCover(this); } return ret; } } catch (Exception ex) { Log.e("loadCover", ex.getMessage(), ex); return false; } return false; }
From source file:com.example.parking.ParkingInformationActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (data != null) { switch (requestCode) { case TAKE_PHOTO: //? if (data.getData() != null || data.getExtras() != null) { // Uri uri = data.getData(); if (uri != null) { if (mEnterImage == null) { mEnterImage = BitmapFactory.decodeFile(uri.getPath()); // }/*from w w w .j av a 2 s . c om*/ } Bundle bundle = data.getExtras(); if (bundle != null) { if (mEnterImage == null) { mEnterImage = (Bitmap) bundle.get("data"); } } } if (mEnterImage != null) { mEnterImageIV.setImageBitmap(mEnterImage); } break; } } }
From source file:au.com.wallaceit.reddinator.Rservice.java
@Override public RemoteViews getViewAt(int position) { RemoteViews row;// w w w .j a v a 2 s. c om if (position > data.length()) { return null; // prevent errornous views } // check if its the last view and return loading view instead of normal row if (position == data.length()) { // build load more item //System.out.println("load more getViewAt("+position+") firing"); RemoteViews loadmorerow = new RemoteViews(mContext.getPackageName(), R.layout.listrowloadmore); if (endOfFeed) { loadmorerow.setTextViewText(R.id.loadmoretxt, "There's nothing more here"); } else { loadmorerow.setTextViewText(R.id.loadmoretxt, "Load more..."); } loadmorerow.setTextColor(R.id.loadmoretxt, themeColors[0]); Intent i = new Intent(); Bundle extras = new Bundle(); extras.putString(WidgetProvider.ITEM_ID, "0"); // zero will be an indicator in the onreceive function of widget provider if its not present it forces a reload i.putExtras(extras); loadmorerow.setOnClickFillInIntent(R.id.listrowloadmore, i); return loadmorerow; } else { // build normal item String title = ""; String url = ""; String permalink = ""; String thumbnail = ""; String domain = ""; String id = ""; int score = 0; int numcomments = 0; boolean nsfw = false; try { JSONObject tempobj = data.getJSONObject(position).getJSONObject("data"); title = tempobj.getString("title"); //userlikes = tempobj.getString("likes"); domain = tempobj.getString("domain"); id = tempobj.getString("name"); url = tempobj.getString("url"); permalink = tempobj.getString("permalink"); thumbnail = (String) tempobj.get("thumbnail"); // we have to call get and cast cause its not in quotes score = tempobj.getInt("score"); numcomments = tempobj.getInt("num_comments"); nsfw = tempobj.getBoolean("over_18"); } catch (JSONException e) { e.printStackTrace(); // return null; // The view is invalid; } // create remote view from specified layout if (bigThumbs) { row = new RemoteViews(mContext.getPackageName(), R.layout.listrowbigthumb); } else { row = new RemoteViews(mContext.getPackageName(), R.layout.listrow); } // build view row.setTextViewText(R.id.listheading, Html.fromHtml(title).toString()); row.setFloat(R.id.listheading, "setTextSize", Integer.valueOf(titleFontSize)); // use for compatibility setTextViewTextSize only introduced in API 16 row.setTextColor(R.id.listheading, themeColors[0]); row.setTextViewText(R.id.sourcetxt, domain); row.setTextColor(R.id.sourcetxt, themeColors[3]); row.setTextColor(R.id.votestxt, themeColors[4]); row.setTextColor(R.id.commentstxt, themeColors[4]); row.setTextViewText(R.id.votestxt, String.valueOf(score)); row.setTextViewText(R.id.commentstxt, String.valueOf(numcomments)); row.setInt(R.id.listdivider, "setBackgroundColor", themeColors[2]); row.setViewVisibility(R.id.nsfwflag, nsfw ? TextView.VISIBLE : TextView.GONE); // add extras and set click intent Intent i = new Intent(); Bundle extras = new Bundle(); extras.putString(WidgetProvider.ITEM_ID, id); extras.putInt("itemposition", position); extras.putString(WidgetProvider.ITEM_URL, url); extras.putString(WidgetProvider.ITEM_PERMALINK, permalink); i.putExtras(extras); row.setOnClickFillInIntent(R.id.listrow, i); // load thumbnail if they are enabled for this widget if (loadThumbnails) { // load big image if preference is set if (!thumbnail.equals("")) { // check for thumbnail; self is used to display the thinking logo on the reddit site, we'll just show nothing for now if (thumbnail.equals("nsfw") || thumbnail.equals("self") || thumbnail.equals("default")) { int resource = 0; switch (thumbnail) { case "nsfw": resource = R.drawable.nsfw; break; case "default": case "self": resource = R.drawable.self_default; break; } row.setImageViewResource(R.id.thumbnail, resource); row.setViewVisibility(R.id.thumbnail, View.VISIBLE); //System.out.println("Loading default image: "+thumbnail); } else { Bitmap bitmap; String fileurl = mContext.getCacheDir() + "/thumbcache-" + appWidgetId + "/" + id + ".png"; // check if the image is in cache if (new File(fileurl).exists()) { bitmap = BitmapFactory.decodeFile(fileurl); saveImageToStorage(bitmap, id); } else { // download the image bitmap = loadImage(thumbnail); } if (bitmap != null) { row.setImageViewBitmap(R.id.thumbnail, bitmap); row.setViewVisibility(R.id.thumbnail, View.VISIBLE); } else { // row.setImageViewResource(R.id.thumbnail, android.R.drawable.stat_notify_error); for later row.setViewVisibility(R.id.thumbnail, View.GONE); } } } else { row.setViewVisibility(R.id.thumbnail, View.GONE); } } else { row.setViewVisibility(R.id.thumbnail, View.GONE); } // hide info bar if options set if (hideInf) { row.setViewVisibility(R.id.infbox, View.GONE); } else { row.setViewVisibility(R.id.infbox, View.VISIBLE); } } //System.out.println("getViewAt("+position+");"); return row; }
From source file:org.yaoha.YaohaActivity.java
public Drawable readDrawableFromSD(String fileName) { File file = new File(getExternalFilesDir(null), fileName); Drawable d;//from ww w. j a v a 2 s . com if (file.exists()) { Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); d = new BitmapDrawable(getResources(), myBitmap); } else { Toast.makeText(this, "Could not find File, loading default picture.", Toast.LENGTH_LONG).show(); d = getResources().getDrawable(R.drawable.placeholder_logo); } return d; }
From source file:fr.bde_eseo.eseomega.profile.ViewProfileFragment.java
public void setImageView() { File fp = new File(profile.getPicturePath()); if (fp.exists()) { Bitmap bmp = ImageUtils.getResizedBitmap(BitmapFactory.decodeFile(profile.getPicturePath()), MainActivity.MAX_PROFILE_SIZE); if (bmp != null) imageView.setImageBitmap(bmp); }//w ww . java 2 s. c o m }
From source file:com.google.plus.wigwamnow.social.FacebookProvider.java
/** * Post a photo from a {@link Uri} to the user's WigwamNow album. *//*from w w w . ja v a 2 s . c o m*/ @Override public boolean postPhoto(Uri photoUri, Activity activity) { final WigwamDetailActivity wda = (WigwamDetailActivity) activity; Session session = Session.getActiveSession(); if (!hasPublishPermissions()) { requestPublishPermissions(session, activity); return false; } String postingPhotoString = activity.getResources().getString(R.string.posting_photo); showProgressDialog(postingPhotoString, activity); Request.Callback callback = new Request.Callback() { @Override public void onCompleted(Response response) { onPostActionResponse(response, wda); } }; Bitmap bitmap = BitmapFactory.decodeFile(photoUri.getPath()); Request request = Request.newUploadPhotoRequest(session, bitmap, callback); request.executeAsync(); return true; }