List of usage examples for android.graphics BitmapFactory decodeByteArray
public static Bitmap decodeByteArray(byte[] data, int offset, int length)
From source file:com.androidrocks.bex.util.ImageUtilities.java
/** * Loads an image from the specified URL with the specified cookie. * * @param url The URL of the image to load. * @param cookie The cookie to use to load the image. * * @return The image at the specified URL or null if an error occured. *//*w w w . j a v a2 s . co m*/ public static ExpiringBitmap load(String url, String cookie) { ExpiringBitmap expiring = new ExpiringBitmap(); final HttpGet get = new HttpGet(url); if (cookie != null) get.setHeader("cookie", cookie); HttpEntity entity = null; try { final HttpResponse response = HttpManager.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { setLastModified(expiring, response); entity = response.getEntity(); InputStream in = null; OutputStream out = null; try { in = entity.getContent(); if (FLAG_DECODE_BITMAP_WITH_SKIA) { expiring.bitmap = BitmapFactory.decodeStream(in); } else { final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); out = new BufferedOutputStream(dataStream, IOUtilities.IO_BUFFER_SIZE); IOUtilities.copy(in, out); out.flush(); final byte[] data = dataStream.toByteArray(); expiring.bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); } } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not load image from " + url, e); } finally { IOUtilities.closeStream(in); IOUtilities.closeStream(out); } } } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not load image from " + url, e); } finally { if (entity != null) { try { entity.consumeContent(); } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not load image from " + url, e); } } } return expiring; }
From source file:com.example.android.camera.CameraActivity.java
@Override protected void onResume() { super.onResume(); Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() { @Override/*from w w w . j a va2s . c om*/ public void onPreviewFrame(byte[] data, Camera camera) { if (notRequesting && mPreview.faces.size() >= 1 && imageFormat == ImageFormat.NV21) { // Block Request. notRequesting = false; try { Camera.Parameters parameters = camera.getParameters(); Size size = parameters.getPreviewSize(); textServerView.setText("Preparing Image to send"); YuvImage previewImg = new YuvImage(data, parameters.getPreviewFormat(), size.width, size.height, null); pWidth = previewImg.getWidth(); pHeight = previewImg.getHeight(); Log.d("face View", "Width: " + pWidth + " x Height: " + pHeight); prepareMatrix(matrix, 0, pWidth, pHeight); List<Rect> foundFaces = getFaces(); for (Rect cRect : foundFaces) { // Cropping ByteArrayOutputStream bao = new ByteArrayOutputStream(); previewImg.compressToJpeg(cRect, 100, bao); byte[] mydata = bao.toByteArray(); // Resizing ByteArrayOutputStream sbao = new ByteArrayOutputStream(); Bitmap bm = BitmapFactory.decodeByteArray(mydata, 0, mydata.length); Bitmap sbm = Bitmap.createScaledBitmap(bm, 100, 100, true); bm.recycle(); sbm.compress(Bitmap.CompressFormat.JPEG, 100, sbao); byte[] mysdata = sbao.toByteArray(); RequestParams params = new RequestParams(); params.put("upload", new ByteArrayInputStream(mysdata), "tmp.jpg"); textServerView.setText("Sending Image to the Server"); FaceMatchClient.post(":8080/match", params, new JsonHttpResponseHandler() { @Override public void onSuccess(JSONArray result) { Log.d("face onSuccess", result.toString()); try { JSONObject myJson = (JSONObject) result.get(0); float dist = (float) Double.parseDouble(myJson.getString("dist")); Log.d("distance", "" + dist); int level = (int) ((1 - dist) * 100); if (level > previousMatchLevel) { textView.setText("Match " + level + "% with " + myJson.getString("name") + " <" + myJson.getString("email") + "> "); loadImage(myJson.getString("classes"), myJson.getString("username")); } previousMatchLevel = level; trialCounter++; if (trialCounter < 100 && level < 74) { textServerView.setText("Retrying..."); notRequesting = true; } else if (trialCounter == 100) { textServerView.setText("Fail..."); } else { textServerView.setText("Found Good Match? If not try again!"); fdButtonClicked = false; trialCounter = 0; previousMatchLevel = 0; mCamera.stopFaceDetection(); button.setText("StartFaceDetection"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // informationView.showInfo(myJson); } }); } textServerView.setText("POST Sent"); textServerView.setText("Awaiting for response"); } catch (Exception e) { e.printStackTrace(); textServerView.setText("Error AsyncPOST"); } } } }; // Open the default i.e. the first rear facing camera. mCamera = Camera.open(); mCamera.setPreviewCallback(previewCallback); // To use front camera // mCamera = Camera.open(CameraActivity.getFrontCameraId()); mPreview.setCamera(mCamera); parameters = mCamera.getParameters(); imageFormat = parameters.getPreviewFormat(); PreviewSize = parameters.getPreviewSize(); }
From source file:net.peterkuterna.android.apps.devoxxfrsched.util.ImageDownloader.java
Bitmap downloadBitmap(String url) { final int IO_BUFFER_SIZE = 4 * 1024; File cacheFile = null;//from w ww . j a va 2 s. com try { MessageDigest mDigest = MessageDigest.getInstance("SHA-1"); mDigest.update(url.getBytes()); final String cacheKey = bytesToHexString(mDigest.digest()); if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android" + File.separator + "data" + File.separator + mContext.getPackageName() + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp"); } } catch (NoSuchAlgorithmException e) { // Oh well, SHA-1 not available (weird), don't cache bitmaps. } HttpGet getRequest = null; try { getRequest = new HttpGet(url); } catch (IllegalArgumentException e) { Log.e(TAG, "Error while constructing get request: " + e.getMessage()); return null; } try { HttpResponse response = mClient.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); return null; } final HttpEntity entity = response.getEntity(); if (entity != null) { final byte[] respBytes = EntityUtils.toByteArray(entity); if (cacheFile != null) { try { cacheFile.getParentFile().mkdirs(); cacheFile.createNewFile(); FileOutputStream fos = new FileOutputStream(cacheFile); fos.write(respBytes); fos.close(); } catch (FileNotFoundException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } catch (IOException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } } return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length); } } catch (IOException e) { getRequest.abort(); Log.w(TAG, "I/O error while retrieving bitmap from " + url, e); } catch (IllegalStateException e) { getRequest.abort(); Log.w(TAG, "Incorrect URL: " + url); } catch (Exception e) { getRequest.abort(); Log.w(TAG, "Error while retrieving bitmap from " + url, e); } return null; }
From source file:com.appdevper.mediaplayer.ui.PlaybackControlsFragment.java
private Bitmap downloadBitmap(String mediaId) { String url = MusicProvider.getInstance().getMusic(mediaId) .getString(MusicProviderSource.CUSTOM_METADATA_TRACK_SOURCE); final MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever(); metaRetriever.setDataSource(url, new HashMap<String, String>()); try {/*from w w w .java 2s . co m*/ final byte[] art = metaRetriever.getEmbeddedPicture(); return BitmapFactory.decodeByteArray(art, 0, art.length); } catch (Exception e) { Log.d(TAG, "Couldn't create album art: " + e.getMessage()); return BitmapFactory.decodeResource(getResources(), R.drawable.ic_default_art); } }
From source file:org.ubicompforall.cityexplorer.gui.PoiDetailsActivity.java
/** * Method fetches information for the current PoI, and shows it in the GUI. * @param poi The poi to fetch information from. *//*w w w . jav a 2s .c o m*/ private void showPoiDetails(Poi poi) { title.setText(poi.getLabel()); description.setText(poi.getDescription()); // address.setText( poi.getAddress().getStreet() + "\n" + poi.getAddress().getZipCode() + "\n" + poi.getAddress().getCity()); // ZIP code removed address.setText(poi.getAddress().getStreet() + "\n" + poi.getAddress().getCity()); category.setText(poi.getCategory()); telephone.setText(poi.getTelephone()); openingHours.setText(poi.getOpeningHours()); webPage.setText(poi.getWebPage()); if (!poi.getImageURL().equals("")) { final String imageURL = poi.getImageURL(); new Thread(new Runnable() { public void run() { try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(imageURL); //have user-inserted url HttpResponse httpResponse; final HttpEntity entity; httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = httpResponse.getEntity(); // TODO: The picture is not shown on Honeycomb SDK or higher (web service calls should be made on a separate thread) // Code should be upgraded to use the Async Task if (entity != null) { //converting into bytemap and inserting into imageView poiImage.post(new Runnable() { public void run() { byte[] imageBytes = new byte[0]; try { imageBytes = EntityUtils.toByteArray(entity); } catch (Throwable t) { debug(0, "t is " + t); // t.printStackTrace(); } poiImage.setImageBitmap( BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length)); } }); } else { debug(0, "entity == null?"); } } else { debug(0, "(httpResponse.getStatusLine().getStatusCode() == not OK "); } } catch (UnknownHostException e) { //Toast.makeText(PoiDetailsActivity.this, "Enable Internet to show Picture", Toast.LENGTH_SHORT ); debug(0, "Enable Internet to show Picture: " + imageURL); } catch (Exception e) { debug(-1, "Error fetching image: " + imageURL); e.printStackTrace(); } //try-catch }//run }//new Runnable class ).start(); } else { poiImage.setImageBitmap(null); } //if img, else blank }
From source file:org.blanco.techmun.android.cproviders.MensajesFetcher.java
public List<Mensaje> getMensajes() { List<Mensaje> result = null; //Do not force the cache load first in order to know if the cache is old or not // result = tryToLoadFromCache(context, false); // if (result != null){ // //If loaded from cache // return result; // }/*from w ww . jav a 2 s .c o m*/ HttpResponse response; boolean retrieved = true; try { result = new ArrayList<Mensaje>(); HttpGet req = new HttpGet(TechMunContentProvider.MESAS_REST_SERVICE_BSAE_URI + "/mensajes"); response = client.execute(req); HttpEntity entity = response.getEntity(); JSONArray mensajes = XmlParser.parseJSONArrayFromHttpEntity(entity); for (int i = 0; i < mensajes.length(); i++) { JSONObject joMensaje = mensajes.getJSONObject(i); String sMensaje = joMensaje.getString("mensaje"); long id = joMensaje.getLong("id"); String sFecha = joMensaje.getString("fecha"); Usuario autor = null; if (joMensaje.has("autor")) { JSONObject joUsuario = joMensaje.getJSONObject("autor"); String saNombre = joUsuario.getString("nombre"); String saCorreo = joUsuario.getString("correo"); autor = new Usuario(saNombre, saCorreo); } Mensaje mensaje = new Mensaje(sMensaje, autor); mensaje.setFecha(new Date(Date.parse(sFecha))); mensaje.setId(id); //try to load the foto of the mensaje String encoded_foto = joMensaje.getString("encoded_foto"); if (encoded_foto != null && !encoded_foto.equals("")) { byte foto[] = Base64Coder.decode(encoded_foto.toCharArray()); mensaje.setFoto(BitmapFactory.decodeByteArray(foto, 0, foto.length)); } result.add(mensaje); } } catch (Exception e) { Log.e("techmun2011", "Error Retrieving Mensajes from internet", e); retrieved = false; } //If there is an error with the connection try to load mensajes from cache if (!retrieved) { result = tryToLoadFromCache(context, true); return result; } //saveOnCache(context, result); return result; }
From source file:com.example.android.apis.graphics.FingerPaint.java
private Bitmap loadBitmap() { SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this); String previouslyEncodedImage = shre.getString("paint_image_data", ""); if (!previouslyEncodedImage.equalsIgnoreCase("")) { byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length); Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true); return mutableBitmap; }//from w w w . j a v a2 s .co m Display display = getWindowManager().getDefaultDisplay(); @SuppressWarnings("deprecation") int width = display.getWidth(); @SuppressWarnings("deprecation") int height = display.getHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); return bitmap; }
From source file:com.ijiaban.yinxiang.MainActivity.java
@SuppressLint("HandlerLeak") @Override//from www. j a v a2s . co m protected void onCreate(Bundle savedInstanceState) { Log.w("MainActivity: onCreate()", "ONCREATE"); super.onCreate(savedInstanceState); ANIMAL = getResources().getString(R.string.Animal); CARTOON = getResources().getString(R.string.Cartoon); LOVE = getResources().getString(R.string.Love); MUSIC = getResources().getString(R.string.Music); SPORTS = getResources().getString(R.string.Sports); BUSINESS = getResources().getString(R.string.Business); CARS = getResources().getString(R.string.Cars); DISHES = getResources().getString(R.string.Dishes); LOCAL = getResources().getString(R.string.Local); setContentView(R.layout.activity_main); MobclickAgent.updateOnlineConfig(this); LinearLayout layout = (LinearLayout) findViewById(R.id.adlayoutmainfragment); mAdView = new AdView(this); mAdView.setAdUnitId(getResources().getString(R.string.ad_unit_id)); mAdView.setAdSize(AdSize.BANNER); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); layout.addView(mAdView, params); mAdView.loadAd(new AdRequest.Builder().build()); // mNameTextView = (TextView) findViewById(R.id.nameTextView); // mDescriptionTextView = (TextView) findViewById(R.id.descriptionTextView); mIconImageView = (ImageView) findViewById(R.id.iconImageView); tabs = (PagerSlidingTabStrip) findViewById(R.id.maintabs); pager = (ViewPager) findViewById(R.id.pager); pagerAdapter = new CommonPagerAdapter(getSupportFragmentManager()); pager.setAdapter(pagerAdapter); final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics()); pager.setPageMargin(pageMargin); tabs.setViewPager(pager); // Check whether we're recreating a previously destroyed instance if (savedInstanceState != null) { Log.d("MainActivity", "onRestoreInstanceState()"); // Always call the superclass so it can restore the view hierarchy super.onRestoreInstanceState(savedInstanceState); // Restore state members from saved instance byte[] imageBytes = savedInstanceState.getByteArray(STORED_IMAGE); if (imageBytes != null) { mGeneratedBitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); } mContact = savedInstanceState.getParcelable(STORED_CONTACT); mHasPickedContact = savedInstanceState.getBoolean(STORED_PICKED); mScreenWidthInPixels = savedInstanceState.getInt(STORED_WIDTH); if (mHasPickedContact && mContact != null && mGeneratedBitmap != null) { Log.d("Restoring generated bitmap", mGeneratedBitmap.getHeight() + ""); Log.d("Restoring contact object", mContact.getFullName()); showContactData(); } } if (!mHasPickedContact) { Log.d("MainActivity: onCreate()", "No contact picked yet."); pickContact(); } }
From source file:com.keithandthegirl.services.download.DownloadService.java
private void saveBitmap(String filename, String urlPath, File output) { Log.v(TAG, "saveBitmap : enter"); try {//from w w w. ja va 2s.c om ResponseEntity<byte[]> responseEntity = template.exchange(urlPath, HttpMethod.GET, entity, byte[].class); switch (responseEntity.getStatusCode()) { case OK: Log.v(TAG, "saveBitmap : file downloaded"); byte[] bytes = responseEntity.getBody(); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); FileOutputStream fos = new FileOutputStream(output); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); result = FragmentActivity.RESULT_OK; break; default: Log.v(TAG, "saveBitmap : file not downloaded"); break; } } catch (Exception e) { Log.e(TAG, "saveBitmap : exit, error", e); } Log.v(TAG, "saveBitmap : exit"); }
From source file:rpassmore.app.fillthathole.ViewHazardActivity.java
private void populateFromHazard() { locationDesc.setText(hazard.getLocationDesc()); // Photo set from photo handlers hazardType.setSelection(hazard.getHazardType()); locationDesc.setText(hazard.getHazardDesc()); // display the thumbnail if (hazard.getPhoto() != null) { image.setImageBitmap(BitmapFactory.decodeByteArray(hazard.getPhoto(), 0, hazard.getPhoto().length)); }/* w w w. j a v a 2 s . com*/ additionalInfo.setChecked(hazard.isHasAdditionalInfo()); hazardDepth.setText(Double.toString(hazard.getDepth())); hazardSize.setText(Double.toString(hazard.getSize())); hazardDistFromKerb.setText(Double.toString(hazard.getDistFromKerb())); onRedRoute.setChecked(hazard.isOnRedRoute()); onLevelCrossing.setChecked(hazard.isOnLevelCrossing()); onTowPath.setChecked(hazard.isOnTowPath()); }