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.sim2dial.dialer.ChatFragment.java

public static Bitmap downloadImage(String stringUrl) {
    URL url;/*from   www. j  a  v a  2s  .  c o  m*/
    Bitmap bm = null;
    try {
        url = new URL(stringUrl);
        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        byte[] rawImage = baf.toByteArray();
        bm = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
        bis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return bm;
}

From source file:com.marekscholtz.bluetify.utilities.BluetoothChatService.java

private void showNotification(Friend friend, ChatMessage chatMessage) {
    if (mHandler == null) {
        Intent clickIntent = new Intent(getApplicationContext(), ChatActivity.class);
        clickIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        clickIntent.putExtra("mac_address", friend.getMacAddress());
        PendingIntent clickPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, clickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.drawable.ic_logo_white_24dp).setPriority(Notification.PRIORITY_HIGH)
                .setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary))
                .setContentTitle(friend.getName()).setContentIntent(clickPendingIntent).setAutoCancel(true);

        if (mSharedPreferences.getBoolean("notification_sound", false)) {
            notificationBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
        }// w w  w  .  j a  v  a  2  s .  c  o  m

        if (mSharedPreferences.getBoolean("notification_vibration", false)) {
            notificationBuilder.setVibrate(new long[] { 0, 250, 250, 250 });
        }

        if (mSharedPreferences.getBoolean("notification_light", false)) {
            notificationBuilder.setLights(0xff0082fc, 1000, 1000);
        }

        if (!chatMessage.hasPicture()) {
            notificationBuilder.setContentText(new String(chatMessage.getContent()));
        } else {
            if (chatMessage.isSent()) {
                notificationBuilder.setContentText(
                        getApplicationContext().getResources().getString(R.string.you_sent_an_image) + ".");
            } else {
                notificationBuilder.setContentText(friend.getName() + " "
                        + getApplicationContext().getResources().getString(R.string.sent_you_an_image) + ".");
            }
        }

        if (friend.getProfilePhoto() != null) {
            byte[] profilePhotoBytes = friend.getProfilePhoto();
            Bitmap profilePhotoBitmap = BitmapFactory.decodeByteArray(friend.getProfilePhoto(), 0,
                    profilePhotoBytes.length);
            notificationBuilder.setLargeIcon(profilePhotoBitmap);
        }

        //TODO reply in notification
        //            if (android.os.Build.VERSION_CODES.N <= android.os.Build.VERSION.SDK_INT) {
        //                PendingIntent replyPendingIntent =
        //                        PendingIntent.getActivity(
        //                                getApplicationContext(),
        //                                0,
        //                                new Intent("REPLY"),
        //                                PendingIntent.FLAG_UPDATE_CURRENT
        //                        );
        //                RemoteInput remoteInput = new RemoteInput.Builder("message_text")
        //                        .setLabel(getString(R.string.write_a_message))
        //                        .build();
        //
        //                NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_send_white_24dp,
        //                        getString(R.string.reply), replyPendingIntent)
        //                        .addRemoteInput(remoteInput)
        //                        .build();
        //
        //                getApplicationContext().registerReceiver(new NotificationBroadcastReceiver(), new IntentFilter("REPLY"));
        //                notificationBuilder.addAction(action);
        //            }

        NotificationManager mNotificationManager = (NotificationManager) getApplicationContext()
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, notificationBuilder.build());
    } else {
        Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(125);
    }
}

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

private void saveImage(int id) {
    try {/*  w ww . j av  a2s.  c  o m*/
        byte[] rawImage = LinphoneActivity.instance().getChatStorage().getRawImageFromMessage(id);
        Bitmap bm = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);

        String path = Environment.getExternalStorageDirectory().toString();
        OutputStream fOut = null;
        File file = new File(path, getString(R.string.picture_name_format).replace("%s", String.valueOf(id)));
        fOut = new FileOutputStream(file);

        bm.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        fOut.flush();
        fOut.close();

        Toast.makeText(getActivity(), getString(R.string.image_saved), Toast.LENGTH_SHORT).show();
        MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), file.getAbsolutePath(),
                file.getName(), file.getName());
    } catch (Exception e) {
        Toast.makeText(getActivity(), getString(R.string.image_not_saved), Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}

From source file:at.flack.MainActivity.java

public static final Bitmap fetchThumbnail(Activity context, String number) {
    Integer id = fetchThumbnailId(context, number);
    if (id == null)
        return null;
    final Uri uri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, id);
    final Cursor cursor = context.getContentResolver().query(uri, SMSItem.PHOTO_BITMAP_PROJECTION, null, null,
            null);//w  w  w  . j a v  a  2  s.c  om

    try {
        Bitmap thumbnail = null;
        if (cursor.moveToFirst()) {
            final byte[] thumbnailBytes = cursor.getBlob(0);
            if (thumbnailBytes != null) {
                thumbnail = BitmapFactory.decodeByteArray(thumbnailBytes, 0, thumbnailBytes.length);
            }
        }
        return thumbnail;
    } finally {
        cursor.close();
    }
}

From source file:com.android.ex.chips.RecipientEditTextView.java

private Bitmap createUnselectedChip(final RecipientEntry contact, final TextPaint paint,
        final boolean leaveBlankIconSpacer) {
    // Ellipsize the text so that it takes AT MOST the entire width of the
    // autocomplete text entry area. Make sure to leave space for padding
    // on the sides.
    final int height = (int) mChipHeight;
    int iconWidth = height;
    final float[] widths = new float[1];
    paint.getTextWidths(" ", widths);
    final float availableWidth = calculateAvailableWidth();
    final String chipDisplayText = createChipDisplayText(contact);
    final CharSequence ellipsizedText = ellipsizeText(chipDisplayText, paint,
            availableWidth - iconWidth - widths[0]);
    // Make sure there is a minimum chip width so the user can ALWAYS
    // tap a chip without difficulty.
    final int width = Math.max(iconWidth * 2,
            (int) Math.floor(paint.measureText(ellipsizedText, 0, ellipsizedText.length())) + mChipPadding * 2
                    + iconWidth);//from w ww.ja  v a  2  s.co m
    // Create the background of the chip.
    final Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(tmpBitmap);
    final Drawable background = getChipBackground(contact);
    if (background != null) {
        background.setBounds(0, 0, width, height);
        background.draw(canvas);
        // Don't draw photos for recipients that have been typed in OR generated on the fly.
        final long contactId = contact.getContactId();
        final boolean drawPhotos = isPhoneQuery() ? contactId != RecipientEntry.INVALID_CONTACT
                : contactId != RecipientEntry.INVALID_CONTACT && contactId != RecipientEntry.GENERATED_CONTACT
                        && !TextUtils.isEmpty(contact.getDisplayName());
        if (drawPhotos) {
            byte[] photoBytes = contact.getPhotoBytes();
            // There may not be a photo yet if anything but the first contact address
            // was selected.
            if (photoBytes == null && contact.getPhotoThumbnailUri() != null) {
                // TODO: cache this in the recipient entry?
                getAdapter().fetchPhoto(contact, contact.getPhotoThumbnailUri());
                photoBytes = contact.getPhotoBytes();
            }
            Bitmap photo;
            if (photoBytes != null)
                photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
            else // TODO: can the scaled down default photo be cached?
                photo = mDefaultContactPhoto;
            // Draw the photo on the left side.
            if (photo != null) {
                final RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight());
                final Rect backgroundPadding = new Rect();
                mChipBackground.getPadding(backgroundPadding);
                final RectF dst = new RectF(width - iconWidth + backgroundPadding.left,
                        0 + backgroundPadding.top, width - backgroundPadding.right,
                        height - backgroundPadding.bottom);
                final Matrix matrix = new Matrix();
                matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
                canvas.drawBitmap(photo, matrix, paint);
            }
        } else if (!leaveBlankIconSpacer || isPhoneQuery())
            iconWidth = 0;
        paint.setColor(ContextCompat.getColor(getContext(), android.R.color.black));
        // Vertically center the text in the chip.
        canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding,
                getTextYOffset((String) ellipsizedText, paint, height), paint);
    } else
        Log.w(TAG, "Unable to draw a background for the chips as it was never set");
    return tmpBitmap;
}

From source file:LPGoogleFunctions.LPGoogleFunctions.java

/**
 * The Google Maps Image APIs make it easy to embed a static Google Maps image into your image view.
 * @param location - The location (such as 40.457375,-80.009353).
 * @param zoomLevel - (required if markers not present) defines the zoom level of the map, which determines the magnification level of the map.
 * This parameter takes a numerical value corresponding to the zoom level of the region desired.
 * @param imageWidth - Specifies width size of the image in pixels.
 * @param imageHeight - Specifies height size of the image in pixels.
 * @param imageScale - (optional) affects the number of pixels that are returned. scale=2 returns twice as many pixels as scale=1 while retaining the same coverage area and level of detail (i.e. the contents of the map don't change).
 * This is useful when developing for high-resolution displays, or when generating a map for printing. The default value is 1.
 * @param mapType - (optional) defines the type of map to construct. There are several possible maptype values, including roadmap, satellite, hybrid, and terrain. Use LPGoogleMapType.
 * @param markers - (optional) define one or more markers to attach to the image at specified locations. This parameter takes a single marker definition with parameters separated by the pipe character (|).
 * Multiple markers may be placed within the same markers parameter as long as they exhibit the same style; you may add additional markers of differing styles by adding additional markers parameters.
 * Note that if you supply markers for a map, you do not need to specify the (normally required) center and zoom parameters. Use LPMapImageMarker.
 * @param responseHandler//from ww w.j a  v a  2s  .c  o m
 * @Override public void willLoadStaticMapImage()
 * @Override public void didLoadStaticMapImage(Bitmap bmp)
 * @Override public void errorLoadingStaticMapImage(Throwable error)
 */

public void loadStaticMapImageForLocation(LPLocation location, int zoomLevel, int imageWidth, int imageHeight,
        int imageScale, LPGoogleMapType mapType, ArrayList<LPMapImageMarker> markers,
        final StaticMapImageListener responseHandler) {
    if (responseHandler != null)
        responseHandler.willLoadStaticMapImage();

    StringBuilder URL = new StringBuilder(googleAPIStaticMapImageURL);

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

    if (location != null)
        URL.append(String.format("center=%s,%s&", coordinateDecimalFormat.format(location.latitude),
                coordinateDecimalFormat.format(location.longitude)));
    URL.append(String.format("sensor=%s&", this.sensor ? "true" : "false"));
    URL.append(String.format("zoom=%d&", zoomLevel));
    URL.append(String.format("scale=%d&", imageScale));
    URL.append(String.format("size=%dx%d&", imageWidth, imageHeight));
    URL.append(String.format("maptype=%s&", LPGoogleFunctions.getMapType(mapType)));

    if (markers != null) {
        for (int i = 0; i < markers.size(); i++) {
            LPMapImageMarker marker = markers.get(i);

            URL.append(String.format("markers=%s&", marker.getMarkerURLString()));
        }
    }

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

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

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

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

From source file:mobisocial.bento.ebento.io.EventManager.java

private Bitmap parseEventImage(Obj object, String eventUuid) {
    Bitmap bitmap = null;/*from  www  .  j  a  v  a2 s.  c om*/
    if (object != null && object.getJson() != null && object.getJson().has(EVENT_IMAGE)) {
        JSONObject imageObj = object.getJson().optJSONObject(EVENT_IMAGE);
        if (eventUuid.equals(imageObj.optString(EVENT_IMAGE_UUID))) {
            byte[] byteArray = Base64.decode(object.getJson().optString(B64JPGTHUMB), Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
        }
    }
    return bitmap;
}

From source file:github.daneren2005.dsub.service.RESTMusicService.java

@Override
public Bitmap getCoverArt(Context context, MusicDirectory.Entry entry, int size, int saveSize,
        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   ww  w . j a  v a  2  s. c o  m*/

        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(), saveSize);
            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);

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

            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            if (size != saveSize) {
                bitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);
            }
            return bitmap;

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

From source file:com.android.launcher3.Utilities.java

public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
    byte[] data = c.getBlob(iconIndex);
    try {/*from   w  w w.j  ava2s . c  om*/
        return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
    } catch (Exception e) {
        return null;
    }
}