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.bamobile.fdtks.util.Tools.java

public static Bitmap createBitmapFromBase64(byte[] base64Data) {
    Bitmap image = null;//  w w  w.  j  a  va2  s .  co  m
    try {
        byte[] imageData = android.util.Base64.decode(base64Data, android.util.Base64.DEFAULT);
        image = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return image;
}

From source file:com.scigames.slidegame.Registration2RFIDActivity.java

public void onActivityResult(int requestCode, Intent data) {
    //public void onActivityResult(int requestCode, int resultCode, Intent data) {     
    super.onActivityResult(requestCode, 1, data);
    Log.d(TAG, "...super.onActivityResult");
    switch (requestCode) {

    case (0): {/*from  w w w. j a va  2 s . c o  m*/
        Log.d(TAG, "...case(0)");
        //if (resultCode == Activity.RESULT_OK) { 
        //  Log.d(TAG,"...RESULT_OK");

        ImageView previewThumbnail = new ImageView(this);
        Log.d(TAG, "...newImageView");

        Bitmap b = BitmapFactory.decodeByteArray(getIntent().getByteArrayExtra("byteArray"), 0,
                getIntent().getByteArrayExtra("byteArray").length);
        Log.d(TAG, "...BitmapFactory.decodeByteArray");

        previewThumbnail.setImageBitmap(b);
        Log.d(TAG, "...setImageBitmap");

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
        Log.d(TAG, "...new layoutparams");

        previewThumbnail.setLayoutParams(layoutParams);
        Log.d(TAG, "...setLayoutParams");
        //}
        break;
    }
    }
}

From source file:com.owncloud.android.ui.activity.ContactListFragment.java

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

    if (vcard != null) {
        // name//from   w  w  w .j  av  a  2  s .co m
        StructuredName name = vcard.getStructuredName();
        if (name != null) {
            String first = (name.getGiven() == null) ? "" : name.getGiven() + " ";
            String last = (name.getFamily() == null) ? "" : name.getFamily();
            holder.getName().setText(first + last);
        } else {
            holder.getName().setText("");
        }

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

            Bitmap thumbnail = BitmapFactory.decodeByteArray(data, 0, data.length);
            RoundedBitmapDrawable drawable = BitmapUtils.bitmapToCircularBitmapDrawable(context.getResources(),
                    thumbnail);

            holder.getBadge().setImageDrawable(drawable);
        } 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()) {
                    vCardClickListener.onVCardCheck(holder.getAdapterPosition());
                } else {
                    vCardClickListener.onVCardUncheck(holder.getAdapterPosition());
                }
            }
        });
    }
}

From source file:com.projectattitude.projectattitude.Activities.ViewProfileActivity.java

/**
 * Initial set up on creation including setting up references, adapters, and readying the search
 * button.//from www  .j a v a2s.  c  om
 * @param savedInstanceState
 */

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_profile);
    searchBar = (EditText) findViewById(R.id.searchBar);
    searchButton = (Button) findViewById(R.id.searchButton);
    removeButton = (Button) findViewById(R.id.removeButton);

    image = (ImageView) findViewById(R.id.profileImage);
    nameView = (TextView) findViewById(R.id.profileUname);

    recentMoodView = (ListView) findViewById(R.id.latestMood);
    followUserList = (ListView) findViewById(R.id.followList);
    followedUserList = (ListView) findViewById(R.id.followedList);

    recentMoodAdapter = new MoodMainAdapter(this, recentMoodList);
    recentMoodView.setAdapter(recentMoodAdapter);

    user = userController.getActiveUser();

    followUserAdapter = new ArrayAdapter<String>(this, R.layout.list_item, user.getFollowList());
    followedUserAdapter = new ArrayAdapter<String>(this, R.layout.list_item, user.getFollowedList());
    followUserList.setAdapter(followUserAdapter);
    followedUserList.setAdapter(followedUserAdapter);

    searchButton.setOnClickListener(new View.OnClickListener() { // adding a new user to following list
        @Override
        public void onClick(View v) {

            String followingName = searchBar.getText().toString();

            User followedUser = new User();
            followedUser.setUserName(followingName);

            if (followingName.equals("")) { // no username entered to search for
                searchBar.requestFocus(); // search has been canceled
            }

            else {
                if (isNetworkAvailable()) {
                    ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask();
                    try {
                        if (getUserTask.execute(followedUser.getUserName()).get() == null) {
                            Log.d("Error", "User did not exist");
                            Toast.makeText(ViewProfileActivity.this, "User not found.", Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            Log.d("Error", "User did exist");
                            //grab user from db and add to following list
                            getUserTask = new ElasticSearchUserController.GetUserTask();
                            try {
                                followedUser = getUserTask.execute(followingName).get();
                                if (followedUser != null) { // user exists
                                    if (followedUser.getUserName().equals(user.getUserName())) {
                                        Toast.makeText(ViewProfileActivity.this,
                                                "You cannot be friends with yourself. Ever", Toast.LENGTH_SHORT)
                                                .show();
                                    } else {
                                        if (user.getFollowList().contains(followedUser.getUserName())) {
                                            Toast.makeText(ViewProfileActivity.this,
                                                    "You're already following that user.", Toast.LENGTH_SHORT)
                                                    .show();
                                        } else {// user not already in list
                                                //check if request between users already exists in database
                                            boolean isContained = false;
                                            ArrayList<FollowRequest> requests = followedUser.getRequests();
                                            for (int i = 0; i < followedUser.getRequests().size(); i++) { //Checks if request already exists
                                                if (requests.get(i).getRequester().equals(user.getUserName())
                                                        && requests.get(i).getRequestee()
                                                                .equals(followedUser.getUserName())) {
                                                    isContained = true;
                                                    break;
                                                }
                                            }
                                            if (!isContained) { //request doesn't exists - not sure why .get always returns an filled array or empty array
                                                followedUser.getRequests().add(new FollowRequest(
                                                        user.getUserName(), followedUser.getUserName()));
                                                ElasticSearchRequestController.UpdateRequestsTask updateRequestsTask = new ElasticSearchRequestController.UpdateRequestsTask();
                                                updateRequestsTask.execute(followedUser);
                                                Toast.makeText(ViewProfileActivity.this, "Request sent!",
                                                        Toast.LENGTH_SHORT).show();
                                            } else { // request exists
                                                Toast.makeText(ViewProfileActivity.this,
                                                        "Request already exists.", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    }
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } catch (ExecutionException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }

                } else {
                    Toast.makeText(ViewProfileActivity.this,
                            "Must be connected to internet to search for users!", Toast.LENGTH_LONG).show();
                }
            }
        }
    });

    //On-click for removeButton
    removeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String followingName = searchBar.getText().toString();

            if (followingName.equals("")) { // no username entered to search for
                searchBar.requestFocus(); // search has been canceled
            }

            else {
                if (isNetworkAvailable()) {
                    if (!user.getFollowList().contains(followingName)) { //If user not in following list
                        Log.d("Error", "Invalid user.");
                        Toast.makeText(ViewProfileActivity.this, "Invalid user. User not found.",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Log.d("Error", "Followed User exists");
                        setResult(RESULT_OK);
                        //remove followedList of who user is following
                        try {
                            ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask();
                            User followedUser = getUserTask.execute(followingName).get();
                            if (followedUser != null) {
                                //Remove followee and update database
                                followedUser.getFollowedList().remove(user.getUserName());
                                ElasticSearchUserController.UpdateUserRequestFollowedTask updateUserRequestFollowedTask = new ElasticSearchUserController.UpdateUserRequestFollowedTask();
                                updateUserRequestFollowedTask.execute(followedUser);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        //user exists --> delete follower and update database
                        user.removeFollow(followingName);
                        ElasticSearchUserController.UpdateUserRequestTask updateUserRequestTask = new ElasticSearchUserController.UpdateUserRequestTask();
                        updateUserRequestTask.execute(user);
                        Toast.makeText(ViewProfileActivity.this, "Followed user has been removed!",
                                Toast.LENGTH_SHORT).show();
                        followUserAdapter.notifyDataSetChanged();
                    }
                } else {
                    Toast.makeText(ViewProfileActivity.this, "Must be connected to internet to remove user!",
                            Toast.LENGTH_LONG).show();
                }
            }
        }
    });

    //If image exists in user, set image
    if (user.getPhoto() != null && user.getPhoto().length() > 0) {
        //decode base64 image stored in User
        byte[] imageBytes = Base64.decode(user.getPhoto(), Base64.DEFAULT);
        Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        image.setImageBitmap(decodedImage);
    }

    /**
     * This handles when a user clicks on their most recent mood, taking them to the view mood screen
     */
    recentMoodView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intentView = new Intent(ViewProfileActivity.this, ViewMoodActivity.class);
            intentView.putExtra("mood", recentMoodList.get(position));
            startActivityForResult(intentView, 1);
        }
    });

    //Adjusted from http://codetheory.in/android-pick-select-image-from-gallery-with-intents/
    //on 3/29/17
    /**
     * This handles when the user clicks on their image
     */
    image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Check if user has permission to get picture from gallery
            if (ContextCompat.checkSelfPermission(thisActivity,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(thisActivity,
                        new String[] { android.Manifest.permission.READ_EXTERNAL_STORAGE },
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            } else { //user already has permission
                Intent intent = new Intent();
                // Show only images, no videos or anything else
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                // Always show the chooser (if there are multiple options available)
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
            }
        }
    });
}

From source file:com.wishlist.Wishlist.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    /*/*from  w  w  w. java  2s.c o  m*/
     * if this is the activity result from authorization flow, do a call back to authorizeCallback
     * Source Tag: login_tag
     */
    case AUTHORIZE_ACTIVITY_RESULT_CODE: {
        Utility.mFacebook.authorizeCallback(requestCode, resultCode, data);
        break;
    }
    /*
     * if this is the result for a photo picker from the gallery, upload the image after scaling it.
     * You can use the Utility.scaleImage() function for scaling
     */
    case PICK_EXISTING_PHOTO_RESULT_CODE: {
        if (resultCode == Activity.RESULT_OK) {
            Uri imageUri = data.getData();
            ((BitmapDrawable) image.getDrawable()).getBitmap().recycle();
            System.gc();
            try {
                imageBytes = Utility.scaleImage(getApplicationContext(), imageUri);
                image.setImageBitmap(BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length));
                image.invalidate();
            } catch (IOException e) {
                showToast(getString(R.string.error_getting_image));
            }
        } else {
            showToast(getString(R.string.no_image_selected));
        }
        break;
    }
    }
}

From source file:no.ntnu.idi.socialhitchhiking.myAccount.MyAccountCar.java

/**
 * Displaying the car information in the layout.
 * @param res/*  w ww.  j a  v a  2 s. com*/
 */
public void showMain(CarResponse res, PreferenceResponse prefResInit) {
    // Initializing the views
    setContentView(R.layout.my_account_car);
    this.imageView = (ImageView) this.findViewById(R.id.cameraView);
    carName = (EditText) this.findViewById(R.id.carName);
    bar = (RatingBar) this.findViewById(R.id.ratingBar1);
    seatsText = (EditText) this.findViewById(R.id.myAccountCarSeats);

    // Setting the number of seats available
    prefRes = prefResInit;
    seatsAvailable = prefRes.getPreferences().getSeatsAvailable();
    if (seatsAvailable > 0) {
        seatsText.setText(seatsAvailable.toString());
    } else {
        seatsText.setText("");
    }

    // If the user does have a car registered
    if (user.getCarId() != 0) {
        // Setting the car name
        carNameString = res.getCar().getCarName();
        // Setting the car ID
        id = res.getCar().getCarId();
        // Setting the comfort
        comfort = (float) res.getCar().getComfort();
        // Getting the car image
        byteArray = res.getCar().getPhoto();

        /*Values of the car from database*/

        // Display these values to the user
        carName.setText(carNameString);
        bar.setRating(comfort);

        String empty = "No car type set";
        byteArrayx = empty.getBytes();
        // If a new image is set, display it
        if (byteArray.length > 15) {
            if (!(res.getCar().getPhotoAsBase64().equals(Base64.encode(byteArrayx, Base64.URL_SAFE)))) {
                btm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
                imageView.setImageBitmap(btm);
            }
        }
        // Indicates that the car is initialized
        isCarInitialized = true;
    }
    //if user does not yet have a car registated
    else {
        carNameString = "";
        id = -1;
        comfort = 0.0f;
        String empty = "No car type set";
        byteArray = empty.getBytes();
    }

    // Setting the button for taking a car picture
    Button photoButton = (Button) this.findViewById(R.id.cameraButton);
    photoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            carChanged = true;
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, "tempName");
            cameraIntent.putExtra("return-data", true);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
    });
    // Setting the button for getting a car picture from the phone
    Button getimageButton = (Button) this.findViewById(R.id.getimageButton);
    getimageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            carChanged = true;
            Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, ALBUM_REQUEST);
        }
    });
}

From source file:org.ros.android.app_chooser.ExchangeActivity.java

public void updateAppDetails() {
    final AppManager man = appManager;
    if (man == null) {
        return;/*from   w w w  . j a va 2s.c o  m*/
    }
    man.getAppDetails(appSelected, new ServiceResponseListener<GetAppDetails.Response>() {
        @Override
        public void onSuccess(GetAppDetails.Response message) {
            final ExchangeApp app = message.app;
            if (app == null) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        revertToState();
                        appDetailView.setVisibility(appDetailView.GONE);
                        new AlertDialog.Builder(ExchangeActivity.this).setTitle("Error on Details Update!")
                                .setCancelable(false)
                                .setMessage("Failed: cannot contact robot! Null application returned")
                                .setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).create().show();
                    }
                });
                return;
            }
            Bitmap bitmap = null;
            if (app.icon.data.length > 0 && app.icon.format != null
                    && (app.icon.format.equals("jpeg") || app.icon.format.equals("png"))) {
                bitmap = BitmapFactory.decodeByteArray(app.icon.data, 0, app.icon.data.length);
            }
            final Bitmap iconBitmap = bitmap;
            Log.i("RosAndroid", "GetInstallationState.Response: " + availableAppsCache.size() + " apps");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ImageView iv = (ImageView) ExchangeActivity.this.findViewById(R.id.exchange_icon);
                    if (iconBitmap != null) {
                        iv.setImageBitmap(iconBitmap);
                    } else {
                        iv.setImageResource(R.drawable.icon);
                    }
                    exchangeAppDetailTextView.setText(app.description.toString());
                    update(availableAppsCache, installedAppsCache);
                }
            });
        }

        @Override
        public void onFailure(final RemoteException e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    revertToState();
                    appDetailView.setVisibility(appDetailView.GONE);
                    new AlertDialog.Builder(ExchangeActivity.this).setTitle("Error on Details Update!")
                            .setCancelable(false).setMessage("Failed: cannot contact robot: " + e.toString())
                            .setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).create().show();
                }
            });
        }
    });
}

From source file:br.com.GUI.perfil.PerfilPersonal.java

public void refresh() {
    bmp = null;/*  ww w . j  ava2s . co  m*/
    Personal rP = new Personal();

    rP = new Personal().buscarPersonal(b, pref.getString("usuario", null));
    //Log.i("Aluno NO RPPPPP", rP.toString());
    try {
        byte[] foto = rP.buscarFotoPersonal(b, pref.getString("usuario", null));
        bmp = BitmapFactory.decodeByteArray(foto, 0, foto.length);
        img.setImageBitmap(bmp);
    } catch (Exception ex) {
        img.setImageDrawable(getResources().getDrawable(R.drawable.profile));
    }

    try {
        nome.setText(rP.getNome());
        if (nome.getText().toString().equals("anyType{}")) {
            nome.setText("");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        if (!rP.getDataDeNascimento().equals("anyType{}") && rP.getDataDeNascimento() != null) {
            String dia = rP.getDataDeNascimento().substring(0, rP.getDataDeNascimento().indexOf("/"));
            String mes = rP.getDataDeNascimento().substring(rP.getDataDeNascimento().indexOf("/") + 1,
                    rP.getDataDeNascimento().lastIndexOf("/"));
            String ano = rP.getDataDeNascimento().substring(rP.getDataDeNascimento().lastIndexOf("/") + 1);

            dataNascimentoDia.setValue(Integer.parseInt(dia));
            dataNascimentoMes.setValue(Integer.parseInt(mes));
            dataNascimentoAno.setValue(Integer.parseInt(ano));
        }
    } catch (Exception e) {
        dataNascimentoDia.setValue(1);
        dataNascimentoMes.setValue(1);
        dataNascimentoAno.setValue(1900);
    }

    try {
        telefone.setText(rP.getTelefone());
        if (telefone.getText().toString().equals("anyType{}")) {
            telefone.setText("");
        }
        email.setText(rP.getEmail());
        if (email.getText().toString().equals("anyType{}")) {
            email.setText("");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.morlunk.mumbleclient.channel.ChannelListAdapter.java

private Drawable getTalkStateDrawable(IUser user) {
    Resources resources = mContext.getResources();
    if (user.isSelfDeafened()) {
        return resources.getDrawable(R.drawable.outline_circle_deafened);
    } else if (user.isDeafened()) {
        return resources.getDrawable(R.drawable.outline_circle_server_deafened);
    } else if (user.isSelfMuted()) {
        return resources.getDrawable(R.drawable.outline_circle_muted);
    } else if (user.isMuted()) {
        return resources.getDrawable(R.drawable.outline_circle_server_muted);
    } else if (user.isSuppressed()) {
        return resources.getDrawable(R.drawable.outline_circle_suppressed);
    } else {/*w  ww . j  a  v a2s  . c o  m*/
        // Passive drawables
        if (user.getTexture() != null) {
            // FIXME: cache bitmaps
            Bitmap bitmap = BitmapFactory.decodeByteArray(user.getTexture(), 0, user.getTexture().length);
            return new CircleDrawable(mContext.getResources(), bitmap);
        } else {
            return resources.getDrawable(R.drawable.outline_circle_talking_off);
        }
    }
}

From source file:com.example.user.lstapp.CreatePlaceFragment.java

private byte[] processPhoto(byte[] data) {
    Log.d(TAG, "picture processing");
    Bitmap originalImg = BitmapFactory.decodeByteArray(data, 0, data.length);

    //resize image
    Bitmap resizedImg = Bitmap.createScaledBitmap(originalImg, (int) (originalImg.getWidth() * 0.2),
            (int) (originalImg.getHeight() * 0.2), true);
    //rotate image to match view for user
    Matrix matrix = new Matrix();
    matrix.postRotate(90);/*from ww  w.  java 2s .  com*/
    Bitmap rotatedImg = Bitmap.createBitmap(resizedImg, 0, 0, resizedImg.getWidth(), resizedImg.getHeight(),
            matrix, true);
    //convert to byte format for sending to server
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    rotatedImg.compress(Bitmap.CompressFormat.PNG, 100, stream);
    return stream.toByteArray();
}