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:com.borqs.browser.combo.BookmarksPageCallbacks.java

private void editBookmark(BrowserBookmarksAdapter adapter, int position) {
    Intent intent = new Intent(this, AddBookmarkPage.class);
    Cursor cursor = adapter.getItem(position);
    Bundle item = new Bundle();
    item.putString(BrowserContract.Bookmarks.TITLE, cursor.getString(BookmarksLoader.COLUMN_INDEX_TITLE));
    item.putString(BrowserContract.Bookmarks.URL, cursor.getString(BookmarksLoader.COLUMN_INDEX_URL));
    byte[] data = cursor.getBlob(BookmarksLoader.COLUMN_INDEX_FAVICON);
    if (data != null) {
        item.putParcelable(BrowserContract.Bookmarks.FAVICON,
                BitmapFactory.decodeByteArray(data, 0, data.length));
    }//  w  w  w . j  a  va2  s  .co m
    item.putLong(BrowserContract.Bookmarks._ID, cursor.getLong(BookmarksLoader.COLUMN_INDEX_ID));
    item.putLong(BrowserContract.Bookmarks.PARENT, cursor.getLong(BookmarksLoader.COLUMN_INDEX_PARENT));
    intent.putExtra(AddBookmarkPage.EXTRA_EDIT_BOOKMARK, item);
    intent.putExtra(AddBookmarkPage.EXTRA_IS_FOLDER,
            cursor.getInt(BookmarksLoader.COLUMN_INDEX_IS_FOLDER) == 1);
    startActivity(intent);
}

From source file:com.sim2dial.dialer.ChatFragment.java

public void onMessageReceived(int id, LinphoneAddress from, LinphoneChatMessage message) {
    if (from.asStringUriOnly().equals(sipUri)) {
        if (message.getText() != null) {
            displayMessage(id, message.getText(), String.valueOf(System.currentTimeMillis()), true, null,
                    messagesLayout);//  w  ww.  ja va  2s . co m
        } else if (message.getExternalBodyUrl() != null) {
            byte[] rawImage = LinphoneActivity.instance().getChatStorage().getRawImageFromMessage(id);
            Bitmap bm = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
            displayImageMessage(id, bm, String.valueOf(System.currentTimeMillis()), true, null, messagesLayout);
        }
        scrollToEnd();
    }
}

From source file:github.madmarty.madsonic.service.RESTMusicService.java

@Override
public Bitmap getCoverArt(Context context, MusicDirectory.Entry entry, int size, boolean saveToFile,
        ProgressListener progressListener) throws Exception {

    // Synchronize on the entry so that we don't download concurrently for the same song.
    synchronized (entry) {

        // Use cached file, if existing.
        Bitmap bitmap = FileUtil.getAlbumArtBitmap(context, entry, size);
        if (bitmap != null) {
            return bitmap;
        }/*from  w  w w.  j  a v a2  s.c om*/

        String url = Util.getRestUrl(context, "getCoverArt");

        InputStream in = null;
        try {
            List<String> parameterNames = Arrays.asList("id", "size");
            List<Object> parameterValues = Arrays.<Object>asList(entry.getCoverArt(), size);
            HttpEntity entity = getEntityForURL(context, url, null, parameterNames, parameterValues,
                    progressListener);
            in = entity.getContent();

            // If content type is XML, an error occured.  Get it.
            String contentType = Util.getContentType(entity);
            if (contentType != null && contentType.startsWith("text/xml")) {
                new ErrorParser(context).parse(new InputStreamReader(in, Constants.UTF_8));
                return null; // Never reached.
            }

            byte[] bytes = Util.toByteArray(in);

            if (saveToFile) {
                OutputStream out = null;
                try {
                    out = new FileOutputStream(FileUtil.getAlbumArtFile(context, entry));
                    out.write(bytes);
                } finally {
                    Util.close(out);
                }
            }

            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

        } finally {
            Util.close(in);
        }
    }
}

From source file:com.owncloud.android.datamodel.ThumbnailsCacheManager.java

public static String addAvatarToCache(String accountName, byte[] avatarData, int dimension) {
    final String imageKey = "a_" + accountName;

    Bitmap bitmap = BitmapFactory.decodeByteArray(avatarData, 0, avatarData.length);
    bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension);
    // Add avatar to cache
    if (bitmap != null) {
        addBitmapToCache(imageKey, bitmap);
    }//w  w w . j  a va 2  s.  co m
    return imageKey;
}

From source file:com.mattprecious.notisync.service.SecondaryService.java

/**
 * @param encodedString//w w  w  .ja  v a 2s . co  m
 * @return bitmap (from given string)
 */
public Bitmap stringToBitmap(String encodedString) {
    if (encodedString != null && !encodedString.equals("")) {
        try {
            byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
            Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
            return bitmap;
        } catch (Exception e) {
            e.getMessage();
            return null;
        }
    }
    return null;
}

From source file:com.example.SmartBoard.MQTTHandler.java

public static Bitmap stringToBitmap(String encodedBitmap) {
    byte[] bitmapBytesOptImg = Base64.decode(encodedBitmap, Base64.DEFAULT);
    return BitmapFactory.decodeByteArray(bitmapBytesOptImg, 0, bitmapBytesOptImg.length);
}

From source file:com.owncloud.android.ui.fragment.contactsbackup.ContactListFragment.java

@Override
public void onBindViewHolder(final ContactListFragment.ContactItemViewHolder holder, final int position) {
    final int verifiedPosition = holder.getAdapterPosition();
    final VCard vcard = vCards.get(verifiedPosition);

    if (vcard != null) {

        if (checkedVCards.contains(position)) {
            holder.getName().setChecked(true);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                holder.getName().getCheckMarkDrawable().setColorFilter(ThemeUtils.primaryAccentColor(),
                        PorterDuff.Mode.SRC_ATOP);
            }//  w  ww.  j  a  v  a 2 s .  c  o m
        } else {
            holder.getName().setChecked(false);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                holder.getName().getCheckMarkDrawable().clearColorFilter();
            }
        }

        holder.getName().setText(getDisplayName(vcard));

        // photo
        if (vcard.getPhotos().size() > 0) {
            Photo firstPhoto = vcard.getPhotos().get(0);
            String url = firstPhoto.getUrl();
            byte[] data = firstPhoto.getData();

            if (data != null && data.length > 0) {
                Bitmap thumbnail = BitmapFactory.decodeByteArray(data, 0, data.length);
                RoundedBitmapDrawable drawable = BitmapUtils
                        .bitmapToCircularBitmapDrawable(context.getResources(), thumbnail);

                holder.getBadge().setImageDrawable(drawable);
            } else if (url != null) {
                ImageView badge = holder.getBadge();
                SimpleTarget target = new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, GlideAnimation glideAnimation) {
                        holder.getBadge().setImageDrawable(resource);
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);
                        holder.getBadge().setImageDrawable(errorDrawable);
                    }
                };
                DisplayUtils.downloadIcon(context, url, target, R.drawable.ic_user, badge.getWidth(),
                        badge.getHeight());
            }
        } else {
            try {
                holder.getBadge()
                        .setImageDrawable(TextDrawable.createNamedAvatar(holder.getName().getText().toString(),
                                context.getResources().getDimension(R.dimen.list_item_avatar_icon_radius)));
            } catch (Exception e) {
                holder.getBadge().setImageResource(R.drawable.ic_user);
            }
        }

        // Checkbox
        holder.setVCardListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                holder.getName().setChecked(!holder.getName().isChecked());

                if (holder.getName().isChecked()) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        holder.getName().getCheckMarkDrawable().setColorFilter(ThemeUtils.primaryAccentColor(),
                                PorterDuff.Mode.SRC_ATOP);
                    }

                    if (!checkedVCards.contains(verifiedPosition)) {
                        checkedVCards.add(verifiedPosition);
                    }
                    if (checkedVCards.size() == 1) {
                        EventBus.getDefault().post(new VCardToggleEvent(true));
                    }
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        holder.getName().getCheckMarkDrawable().clearColorFilter();
                    }

                    if (checkedVCards.contains(verifiedPosition)) {
                        checkedVCards.remove(verifiedPosition);
                    }

                    if (checkedVCards.size() == 0) {
                        EventBus.getDefault().post(new VCardToggleEvent(false));
                    }
                }
            }
        });
    }
}

From source file:tr.com.turkcellteknoloji.turkcellupdater.UpdaterDialogManager.java

@SuppressLint("NewApi")
private static View createMessageDialogContentsView(Activity activity, MessageDescription messageDescription) {

    Context context = activity;//from  w ww  .  ja v  a  2  s. c  om

    final AlertDialog.Builder builder;

    // Workaround for dialog theme problems
    if (android.os.Build.VERSION.SDK_INT > 10) {
        builder = new AlertDialog.Builder(context);
        context = builder.getContext();
    } else {
        context = new ContextThemeWrapper(context, android.R.style.Theme_Dialog);
        builder = new AlertDialog.Builder(context);
    }

    builder.setTitle("Send feedback");

    final LayoutInflater inflater = LayoutInflater.from(context);
    final View dialogContentsView = inflater.inflate(R.layout.updater_dialog_message, null, false);
    final TextView textView = (TextView) dialogContentsView.findViewById(R.id.dialog_update_message_text);
    final ImageView imageView = (ImageView) dialogContentsView.findViewById(R.id.dialog_update_message_image);
    final ViewSwitcher switcher = (ViewSwitcher) dialogContentsView
            .findViewById(R.id.dialog_update_message_switcher);

    String messageText = null;
    String imageUrl = null;

    if (messageDescription != null) {
        messageText = messageDescription.get(MessageDescription.KEY_MESSAGE);
        imageUrl = messageDescription.get(MessageDescription.KEY_IMAGE_URL);
    }

    if (Utilities.isNullOrEmpty(messageText)) {
        textView.setVisibility(View.GONE);
    } else {
        textView.setText(messageText);
    }

    if (Utilities.isNullOrEmpty(imageUrl)) {
        switcher.setVisibility(View.GONE);
    } else {
        URI uri;
        try {
            uri = new URI(imageUrl);
        } catch (URISyntaxException e) {
            uri = null;
        }

        if (uri != null) {
            DownloadRequest request = new DownloadRequest();
            request.setUri(uri);
            request.setDownloadHandler(new DownloadHandler() {

                @Override
                public void onSuccess(byte[] result) {
                    // Load image from byte array
                    final Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
                    imageView.setImageBitmap(bitmap);

                    // Hide progress bar and display image
                    if (switcher != null) {
                        switcher.setDisplayedChild(1);
                    }
                }

                @Override
                public void onProgress(Integer percent) {

                }

                @Override
                public void onFail(Exception ex) {
                    Log.e("Message image couldn't be loaded", ex);
                }

                @Override
                public void onCancelled() {

                }
            });
            HttpClient client = Utilities.createClient("Turkcell Updater/1.0 ", false);
            try {
                request.executeAsync(client);
            } catch (Exception e) {
                Log.e("Message image couldn't be loaded", e);
            }

        } else {
            switcher.setVisibility(View.GONE);
        }

    }

    return dialogContentsView;
}

From source file:LPGoogleFunctions.LPGoogleFunctions.java

/**
 * The Google Maps Image APIs make it easy to embed a street view image into your image view.
 * @param address - The address (such as Chagrin Falls, OH).
 * @param imageWidth - Specifies width size of the image in pixels.
 * @param imageHeight - Specifies height size of the image in pixels.
 * @param heading - Indicates the compass heading of the camera. Accepted values are from 0 to 360 (both values indicating North, with 90 indicating East, and 180 South). 
 * If no heading is specified, a value will be calculated that directs the camera towards the specified location, from the point at which the closest photograph was taken.
 * @param fov - Determines the horizontal field of view of the image. The field of view is expressed in degrees, with a maximum allowed value of 120.
 * When dealing with a fixed-size viewport, as with a Street View image of a set size, field of view in essence represents zoom, with smaller numbers indicating a higher level of zoom.
 * @param pitch- Specifies the up or down angle of the camera relative to the Street View vehicle. This is often, but not always, flat horizontal.
 * Positive values angle the camera up (with 90 degrees indicating straight up).
 * Negative values angle the camera down (with -90 indicating straight down).
 * @param responseHandler/* w w w  . ja v a 2 s  .com*/
 * @Override public void willLoadStreetViewImage();
 * @Override public void didLoadStreetViewImage(Bitmap bmp)
 * @Override public void errorLoadingStreetViewImage(Throwable error);
 */

public void loadStreetViewImageForAddress(String address, int imageWidth, int imageHeight, float heading,
        float fov, float pitch, final StreetViewImageListener responseHandler) {
    if (responseHandler != null)
        responseHandler.willLoadStreetViewImage();

    RequestParams parameters = new RequestParams();

    DecimalFormatSymbols separator = new DecimalFormatSymbols();
    separator.setDecimalSeparator('.');
    DecimalFormat coordinateDecimalFormat = new DecimalFormat("##.######");
    coordinateDecimalFormat.setDecimalFormatSymbols(separator);

    DecimalFormat twoDecimalFormat = new DecimalFormat(".##");
    twoDecimalFormat.setDecimalFormatSymbols(separator);

    parameters.put("key", this.googleAPIBrowserKey);
    parameters.put("sensor", sensor ? "true" : "false");
    parameters.put("size", String.format("%dx%d", imageWidth, imageHeight));
    if (address != null)
        parameters.put("location", address);
    parameters.put("heading", twoDecimalFormat.format(heading));
    parameters.put("fov", twoDecimalFormat.format(fov));
    parameters.put("pitch", twoDecimalFormat.format(pitch));

    this.client.get(googleAPIStreetViewImageURL, parameters, new BinaryHttpResponseHandler() {
        @Override
        public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
            if (responseHandler != null)
                responseHandler.errorLoadingStreetViewImage(arg3);
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
            try {
                Bitmap bmp = BitmapFactory.decodeByteArray(arg2, 0, arg2.length);

                if (responseHandler != null)
                    responseHandler.didLoadStreetViewImage(bmp);
            } catch (Exception e) {
                e.printStackTrace();

                if (responseHandler != null)
                    responseHandler.errorLoadingStreetViewImage(e.getCause());
            }
        }
    });
}

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

@SuppressWarnings("WrongConstant")
private Friend showFriend(Intent intent) {
    T.UI();/*from  www  .jav a2 s. c o  m*/

    final Friend friend = loadFriend(intent);
    if (friend == null) {
        return null;
    }

    mServiceArea.setVisibility(getServiceAreaVisibility());
    mPokeArea.setVisibility(getPokeVisibility());
    mFriendArea.setVisibility(getFriendAreaVisibility());
    mHeader.setVisibility(getHeaderVisibility());

    final ImageView image = (ImageView) findViewById(R.id.friend_avatar);
    if (friend.avatar == null) {
        image.setImageBitmap(mFriendsPlugin.getMissingFriendAvatarBitmap());
    } else {
        final Bitmap avatarBitmap = BitmapFactory.decodeByteArray(friend.avatar, 0, friend.avatar.length);
        image.setImageBitmap(ImageHelper.getRoundedCornerAvatar(avatarBitmap));
    }

    final TextView nameView = (TextView) findViewById(R.id.friend_name);
    mFriendName = friend.getDisplayName();
    nameView.setText(mFriendName);
    nameView.setTextColor(ContextCompat.getColor(this, android.R.color.primary_text_light));

    final TextView emailView = (TextView) findViewById(R.id.email);
    emailView.setText(friend.getDisplayEmail());
    emailView.setTextColor(nameView.getTextColors());

    if (friend.existenceStatus == Friend.NOT_FOUND || friend.existenceStatus == Friend.INVITE_PENDING) {
        final Button pokeBtn = (Button) findViewById(R.id.poke_button);
        pokeBtn.setText(R.string.follow);
        pokeBtn.setOnClickListener(new SafeViewOnClickListener() {
            @Override
            public void safeOnClick(View v) {
                if (mFriendsPlugin.inviteService(mFriend)) {
                    finish();
                }
            }
        });
    } else if (TextUtils.isEmptyOrWhitespace(friend.pokeDescription)) {
        findViewById(R.id.poke_area).setVisibility(View.GONE);
    } else {
        findViewById(R.id.poke_area).setVisibility(View.VISIBLE);
        final Button pokeBtn = (Button) findViewById(R.id.poke_button);
        pokeBtn.setText(friend.pokeDescription);
        pokeBtn.setOnClickListener(new SafeViewOnClickListener() {
            @Override
            public void safeOnClick(View v) {
                T.UI();
                poke();
            }
        });
    }

    mDescriptionView.setText(friend.description);

    if (friend.descriptionBranding != null) {
        boolean available = false;
        try {
            available = mFriendsPlugin.getBrandingMgr().isBrandingAvailable(friend.descriptionBranding);
        } catch (BrandingFailureException e) {
            // ignore
        }
        if (available) {
            showBrandedDescription(friend);
        } else {
            mFriendsPlugin.getBrandingMgr().queue(friend);
        }
    } else {
        mDescriptionView.setVisibility(View.VISIBLE);
        mServiceArea.findViewById(R.id.webview).setVisibility(View.GONE);
        mTopArea.setBackgroundResource(R.color.mc_background_color);
    }

    final CheckBox iShareLocationCheckBox = (CheckBox) findViewById(R.id.share_location);
    iShareLocationCheckBox.setOnCheckedChangeListener(null);
    iShareLocationCheckBox.setChecked(friend.shareLocation);
    iShareLocationCheckBox.setText(getString(R.string.friend_share_location));

    iShareLocationCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            T.UI();
            mFriendsPlugin.updateFriendShareLocation(friend.email, isChecked);
        }
    });

    dismissDialogs();

    return friend;
}