Example usage for android.graphics BitmapFactory decodeByteArray

List of usage examples for android.graphics BitmapFactory decodeByteArray

Introduction

In this page you can find the example usage for android.graphics BitmapFactory decodeByteArray.

Prototype

public static Bitmap decodeByteArray(byte[] data, int offset, int length) 

Source Link

Document

Decode an immutable bitmap from the specified byte array.

Usage

From source file:at.ac.uniklu.mobile.sportal.util.Utils.java

/**
 * Loads a bitmap for the network or from a cached file, if it has already been downloaded before. If the file
 * is loaded for the first time, it is written to the cache to be available next time.
 * //from  w  w w  .  ja va  2  s  .c  om
 * @param context
 * @param sourceUrl
 * @param cacheFileName
 * @return a bitmap or null if something went wrong
 */
public static Bitmap downloadBitmapWithCache(Context context, String sourceUrl, String cacheFileName)
        throws Exception {
    Bitmap bitmap = null;
    File cacheFile = new File(context.getCacheDir(), cacheFileName);

    boolean cached = cacheFile.exists();
    boolean cachedValid = cached && cacheFile.lastModified() > (System.currentTimeMillis() - MILLIS_PER_WEEK);

    if (cached && cachedValid) {
        // the requested file is cached, load it
        Log.d(TAG, "loading cached file: " + cacheFileName);
        bitmap = BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
    } else {
        // the requested file is not cached, download it from the network
        Log.d(TAG, "file " + (cachedValid ? "too old" : "not cached") + ", downloading: " + sourceUrl);
        byte[] data = downloadFile(sourceUrl, 3);
        if (data != null) {
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            if (bitmap != null) {
                // the download succeeded, cache the file so it is available next time
                FileOutputStream out = new FileOutputStream(cacheFile);
                out.write(data, 0, data.length);
                out.flush();
                out.close();
            } else {
                Log.e(TAG, "failed to download bitmap, may be an unsupported format: " + sourceUrl);
            }
        }
    }

    return bitmap;
}

From source file:com.pursuer.reader.easyrss.network.SubscriptionDataSyncer.java

private void syncSubscriptionIcons() throws DataSyncerException {
    final Context context = dataMgr.getContext();
    if (!NetworkUtils.checkSyncingNetworkStatus(context, networkConfig)) {
        return;/*from  ww w . j  a v a  2 s  . c o m*/
    }
    final ContentResolver resolver = context.getContentResolver();
    final Cursor cur = resolver.query(Subscription.CONTENT_URI,
            new String[] { Subscription._UID, Subscription._ICON, Subscription._URL }, null, null, null);
    for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
        final String uid = cur.getString(0);
        final byte[] data = cur.getBlob(1);
        final String subUrl = cur.getString(2);
        if (subUrl != null && data == null) {
            final SubscriptionIconUrl fetchUrl = new SubscriptionIconUrl(isHttpsConnection, subUrl);
            try {
                final byte[] iconData = httpGetQueryByte(fetchUrl);
                final Bitmap icon = BitmapFactory.decodeByteArray(iconData, 0, iconData.length);
                final int size = icon.getWidth() * icon.getHeight() * 2;
                final ByteArrayOutputStream output = new ByteArrayOutputStream(size);
                icon.compress(Bitmap.CompressFormat.PNG, 100, output);
                output.flush();
                output.close();
                dataMgr.updateSubscriptionIconByUid(uid, output.toByteArray());
            } catch (final IOException exception) {
                cur.close();
                throw new DataSyncerException(exception);
            }
        }
    }
    cur.close();
}

From source file:com.vk.sdk.VKCaptchaDialog.java

private void loadImage() {
    VKHttpOperation imageOperation = new VKHttpOperation(new HttpGet(mCaptchaError.captchaImg));
    imageOperation.setHttpOperationListener(new VKHTTPOperationCompleteListener() {
        @Override// www  .  ja  v  a  2s. c o m
        public void onComplete(VKHttpOperation operation, byte[] response) {
            Bitmap captchaImage = BitmapFactory.decodeByteArray(response, 0, response.length);
            captchaImage = Bitmap.createScaledBitmap(captchaImage, (int) (captchaImage.getWidth() * mDensity),
                    (int) (captchaImage.getHeight() * mDensity), true);
            mCaptchaImage.setImageBitmap(captchaImage);
            mCaptchaImage.setVisibility(View.VISIBLE);
            mProgressBar.setVisibility(View.GONE);
        }

        @Override
        public void onError(VKHttpOperation operation, VKError error) {
            loadImage();
        }
    });
    VKHttpClient.enqueueOperation(imageOperation);
}

From source file:com.andernity.launcher2.InstallShortcutReceiver.java

private static ArrayList<PendingInstallShortcutInfo> getAndClearInstallQueue(SharedPreferences sharedPrefs) {
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (strings == null) {
            return new ArrayList<PendingInstallShortcutInfo>();
        }//from w  w  w  . j  ava 2s.c  om
        ArrayList<PendingInstallShortcutInfo> infos = new ArrayList<PendingInstallShortcutInfo>();
        for (String json : strings) {
            try {
                JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                Intent data = Intent.parseUri(object.getString(DATA_INTENT_KEY), 0);
                Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);
                String name = object.getString(NAME_KEY);
                String iconBase64 = object.optString(ICON_KEY);
                String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY);
                String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY);
                if (iconBase64 != null && !iconBase64.isEmpty()) {
                    byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT);
                    Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length);
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b);
                } else if (iconResourceName != null && !iconResourceName.isEmpty()) {
                    Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource();
                    iconResource.resourceName = iconResourceName;
                    iconResource.packageName = iconResourcePackageName;
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
                }
                data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
                PendingInstallShortcutInfo info = new PendingInstallShortcutInfo(data, name, launchIntent);
                infos.add(info);
            } catch (org.json.JSONException e) {
                Log.d("InstallShortcutReceiver", "Exception reading shortcut to add: " + e);
            } catch (java.net.URISyntaxException e) {
                Log.d("InstallShortcutReceiver", "Exception reading shortcut to add: " + e);
            }
        }
        sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>()).commit();
        return infos;
    }
}

From source file:com.cmput301w15t15.travelclaimsapp.activitys.EditExpenseActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.edit_expense);

    sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.CANADA);
    expenseName = this.getIntent().getExtras().getString("expenseName");
    claimName = this.getIntent().getExtras().getString("claimName");

    date = (EditText) findViewById(R.id.Edit_Expense_Date2);
    expenseNameInput = (EditText) findViewById(R.id.Edit_Expense_Name2);
    expenseCostInput = (EditText) findViewById(R.id.Edit_Expense_Cost2);
    expenseDescriptionInput = (EditText) findViewById(R.id.Edit_Expense_Description2);
    currencySpinner = (Spinner) findViewById(R.id.CurrencySpinner2);
    categorySpinner = (Spinner) findViewById(R.id.CategorySpinner2);
    expenseReceiptView = (ImageView) findViewById(R.id.Edit_Expense_Image2);

    claimList = ClaimListController.getClaimList();
    claim = claimList.getClaim(claimName);
    expenseList = claim.getExpenseList();
    expense = expenseList.getExpense(expenseName);

    // show initial image
    if (expense.getPicture() != null) {
        imgShow = expense.getPicture();// w  ww  . j a v a  2s  . c om

        Bitmap bm = BitmapFactory.decodeByteArray(imgShow, 0, imgShow.length);
        sizeNum = imgShow.length;
        size = sizeNum.toString();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        expenseReceiptView.setMinimumHeight(dm.heightPixels);
        expenseReceiptView.setMinimumWidth(dm.widthPixels);
        expenseReceiptView.setImageBitmap(bm);
    }

    expenseReceiptView.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            // Create the Intent for Image Gallery.
            Intent i = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            // Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
            startActivityForResult(i, 1);
            return true;
        }
    });

    expenseReceiptView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            loadPhoto((ImageView) v, 100, 100);
        }
    });

    currencySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            expense.setCurr(parent.getItemAtPosition(position).toString());

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }

    });

    categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            expense.setCat(parent.getItemAtPosition(position).toString());
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }

    });
    set_on_click();
}

From source file:at.florian_lentsch.expirysync.EditProductActivity.java

/**
 * fill all the form fields with {@link #curEntry}'s data
 *//*w ww.  j  a  va 2 s .  c  o  m*/
private void setupEditForm() {
    Bundle bundle = getIntent().getExtras();
    int id = bundle.getInt(ProductListActivity.EXTRA_PRODUCT_ENTRY_ID);
    this.curEntry = DatabaseManager.getInstance().getProductEntryById(id);

    Article article = this.curEntry.article;
    ((EditText) findViewById(R.id.barcode_field)).setText(article.barcode);
    ((EditText) findViewById(R.id.product_name_field)).setText(article.name);
    ((EditText) findViewById(R.id.product_description_field)).setText(this.curEntry.description);
    ((EditText) findViewById(R.id.amount_field)).setText(Integer.toString(this.curEntry.amount));
    if (this.photoPath == null) {
        ArticleImage image = this.curEntry.article.getBestImage();
        if (image != null) {
            if (image.imageData != null) {
                Bitmap bmp = BitmapFactory.decodeByteArray(image.imageData, 0, image.imageData.length);
                ((ImageView) findViewById(R.id.product_img)).setImageBitmap(bmp);
            } else {
                // there is an image, but don't have its data in the local db
                // -> download it from the server:
                final SharedPreferences sharedPref = this.getApplicationContext().getSharedPreferences("main",
                        Context.MODE_PRIVATE);
                String hostStr = sharedPref.getString(SettingsActivity.KEY_HOST, "");
                new DownloadImageTask((ImageView) findViewById(R.id.product_img), image)
                        .execute(hostStr + "article_images/" + image.serverId + "/serve");
            }
        }
    }

    Date expirationDate = this.curEntry.expiration_date;
    Calendar cal = Calendar.getInstance();
    cal.setTime(expirationDate);
    int year = cal.get(Calendar.YEAR), month = cal.get(Calendar.MONTH), day = cal.get(Calendar.DAY_OF_MONTH);
    ((DatePicker) findViewById(R.id.expiration_date_field)).updateDate(year, month, day);
}

From source file:com.trail.octo.Identity.java

public void loaddata() {
    byte[] decodedString;
    String encodedmessage = "";

    encodedmessage = sharedPreferences.getString("pancard", "Empty");
    if (!(encodedmessage.equals("Empty") || encodedmessage.isEmpty())) {
        decodedString = Base64.decode(encodedmessage, Base64.DEFAULT);
        pan_card = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    }/*w w w . jav a2s  . c  o m*/

    encodedmessage = sharedPreferences.getString("drivinglicense", "Empty");
    if (!(encodedmessage.equals("Empty") || encodedmessage.isEmpty())) {
        decodedString = Base64.decode(encodedmessage, Base64.DEFAULT);
        driving_license = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    }

    encodedmessage = sharedPreferences.getString("voterid", "Empty");
    if (!(encodedmessage.equals("Empty") || encodedmessage.isEmpty())) {
        decodedString = Base64.decode(encodedmessage, Base64.DEFAULT);
        voter_id = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    }

    encodedmessage = sharedPreferences.getString("aadharcard", "Empty");
    if (!(encodedmessage.equals("Empty") || encodedmessage.isEmpty())) {
        decodedString = Base64.decode(encodedmessage, Base64.DEFAULT);
        aadhar_card = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    }

    encodedmessage = sharedPreferences.getString("passport", "Empty");
    if (!(encodedmessage.equals("Empty") || encodedmessage.isEmpty())) {
        decodedString = Base64.decode(encodedmessage, Base64.DEFAULT);
        passport = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    }
}

From source file:fr.outadev.skinswitch.MojangAccountSkin.java

@Override
public void downloadSkinFromSource(Context context) throws HttpRequest.HttpRequestException, IOException {
    if (getUuid() == null) {
        return;/*from w  w  w .ja  va  2  s .com*/
    }

    //we have to request a file on Mojang's server if we wanna retrieve the player's skin from his UUID.
    String body = HttpRequest.get(SESSION_API_URL + getUuid()).useCaches(false).body();

    if (body == null) {
        throw new HttpRequest.HttpRequestException(new IOException("Response to get the skin URL was empty."));
    }

    //we're expecting a JSON document that looks like this:
    /*
       {
     ...
     "properties": [
         {
             "name": "textures",
             "value": "<base64 string>"
         }
     ]
       }
     */

    try {
        //trying to reach the properties.value string
        JSONObject obj = new JSONObject(body);
        JSONArray properties = obj.getJSONArray("properties");

        if (properties != null) {
            for (int i = 0; i < properties.length(); i++) {
                if (properties.getJSONObject(i).getString("name").equals("textures")) {
                    //once that string is reached, we have to decode it: it's in base64
                    String base64info = properties.getJSONObject(i).getString("value");
                    JSONObject textureInfo = new JSONObject(
                            new String(Base64.decode(base64info, Base64.DEFAULT)));

                    //the decoded string is also a JSON document, so we parse that. should look like this:
                    /*
                       {
                           ...
                           "textures": {
                     "SKIN": {
                         "url": "<player skin URL>"
                     },
                     ...
                           }
                       }
                     */

                    //we want to retrieve the textures.SKIN.url string. that's the skin's URL. /FINALLY/.
                    String url = textureInfo.getJSONObject("textures").getJSONObject("SKIN").getString("url");

                    if (url != null) {
                        //download the skin from the provided URL
                        byte[] response = HttpRequest.get(url).useCaches(true).bytes();

                        if (response == null) {
                            throw new HttpRequest.HttpRequestException(
                                    new IOException("Couldn't download " + this));
                        }

                        //decode the bitmap and store it
                        Bitmap bmp = BitmapFactory.decodeByteArray(response, 0, response.length);

                        if (bmp != null) {
                            deleteAllCacheFilesFromFilesystem(context);
                            saveRawSkinBitmap(context, bmp);
                            bmp.recycle();
                        }
                    }
                }
            }
        }
    } catch (JSONException e) {
        throw new HttpRequest.HttpRequestException(
                new IOException("The response from Mojang was invalid. Woops."));
    }
}

From source file:com.rastating.droidbeard.net.SickbeardAsyncTask.java

protected Bitmap getBitmap(String cmd, List<Pair<String, Object>> params) {
    Bitmap bitmap = null;//from w w  w  .jav a2s.  c o  m
    Preferences preferences = new Preferences(mContext);
    String format = "%sapi/%s/?cmd=%s";

    String uri = String.format(format, preferences.getSickbeardUrl(), preferences.getApiKey(), cmd);
    if (params != null) {
        for (Pair<String, Object> pair : params) {
            uri += "&" + pair.first + "=" + pair.second.toString();
        }
    }

    try {
        HttpClient client = HttpClientManager.INSTANCE.getClient();
        HttpGet request = new HttpGet(uri);
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);
            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        }
    } catch (MalformedURLException e) {
        mLastException = new SickBeardException("", e);
        e.printStackTrace();
    } catch (IOException e) {
        mLastException = new SickBeardException("", e);
        e.printStackTrace();
    }

    return bitmap;
}

From source file:com.mobicage.rogerthat.FriendDetailOrInviteActivity.java

private void updateView() {
    final ImageView image = (ImageView) findViewById(R.id.friend_avatar);

    if (mFriend == null) {
        image.setVisibility(View.INVISIBLE);
        return;//w w  w. j  a v  a 2 s  .c om
    }
    image.setVisibility(View.VISIBLE);
    final TextView nameView = (TextView) findViewById(R.id.friend_name);

    if (mFriend.avatar == null) {
        image.setImageBitmap(mFriendsPlugin.getMissingFriendAvatarBitmap());
    } else {
        final Bitmap avatarBitmap = BitmapFactory.decodeByteArray(mFriend.avatar, 0, mFriend.avatar.length);
        image.setImageBitmap(ImageHelper.getRoundedCornerAvatar(avatarBitmap));
    }

    setTitle(mFriend.getDisplayName());
    nameView.setText(mFriend.getDisplayName());
    nameView.setTextColor(ContextCompat.getColor(this, android.R.color.primary_text_light));

    final LinearLayout profileDataContainer = (LinearLayout) findViewById(R.id.profile_data);
    if (AppConstants.PROFILE_DATA_FIELDS.length > 0) {
        profileDataContainer.removeAllViews();
        profileDataContainer.setVisibility(View.VISIBLE);
        Map<String, String> profileData = mFriend.getProfileDataDict();
        for (String k : AppConstants.PROFILE_DATA_FIELDS) {
            final LinearLayout ll = (LinearLayout) View.inflate(this, R.layout.profile_data_detail, null);
            final TextView tvKey = (TextView) ll.findViewById(R.id.profile_data_detail_key);
            final TextView tvVal = (TextView) ll.findViewById(R.id.profile_data_detail_value);

            String v = profileData == null ? null : profileData.get(k);
            if (v == null) {
                v = getString(R.string.unknown);
            }
            tvKey.setText(k);
            tvKey.setTextColor(LookAndFeelConstants.getPrimaryColor(this));
            tvVal.setText(v);

            profileDataContainer.addView(ll);
        }
    } else {
        profileDataContainer.setVisibility(View.GONE);
    }
}