Example usage for android.graphics Bitmap createScaledBitmap

List of usage examples for android.graphics Bitmap createScaledBitmap

Introduction

In this page you can find the example usage for android.graphics Bitmap createScaledBitmap.

Prototype

public static Bitmap createScaledBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight, boolean filter) 

Source Link

Document

Creates a new bitmap, scaled from an existing bitmap, when possible.

Usage

From source file:com.emmaguy.todayilearned.PanView.java

private void updateScaledImage() {
    if (mImage == null) {
        return;//from w ww  .jav  a  2s  . co  m
    }
    int width = mImage.getWidth();
    int height = mImage.getHeight();
    if (width > height) {
        float scalingFactor = mHeight * 1f / height;
        mScaledImage = Bitmap.createScaledBitmap(mImage, (int) (scalingFactor * width), mHeight, true);
    } else {
        float scalingFactor = mWidth * 1f / width;
        mScaledImage = Bitmap.createScaledBitmap(mImage, mWidth, (int) (scalingFactor * height), true);
    }

    // Center the image
    mOffsetX = (mWidth - mScaledImage.getWidth()) / 2;
    mOffsetY = (mHeight - mScaledImage.getHeight()) / 2;
    invalidate();
}

From source file:net.kourlas.voipms_sms.notifications.Notifications.java

/**
 * Shows a notification with the specified details.
 *
 * @param contact   The contact that the notification is from.
 * @param shortText The short form of the message text.
 * @param longText  The long form of the message text.
 *///  w  ww  . j a  v a  2s .  c  om
private void showNotification(String contact, String shortText, String longText) {

    String title = Utils.getContactName(applicationContext, contact);
    if (title == null) {
        title = Utils.getFormattedPhoneNumber(contact);
    }
    NotificationCompat.Builder notification = new NotificationCompat.Builder(applicationContext);
    notification.setContentTitle(title);
    notification.setContentText(shortText);
    notification.setSmallIcon(R.drawable.ic_chat_white_24dp);
    notification.setPriority(Notification.PRIORITY_HIGH);
    String notificationSound = Preferences.getInstance(applicationContext).getNotificationSound();
    if (!notificationSound.equals("")) {
        notification.setSound(Uri.parse(Preferences.getInstance(applicationContext).getNotificationSound()));
    }
    String num = Utils.getFormattedPhoneNumber(contact);
    Log.v("prior", num);

    SharedPreferences sharedPreferences = applicationContext.getSharedPreferences("ledData",
            Context.MODE_PRIVATE);
    String cNm = sharedPreferences.getString(title, "3000");
    SharedPreferences sharedPref = applicationContext.getSharedPreferences("color", Context.MODE_PRIVATE);
    int clr = sharedPref.getInt(title, 0xFF02ffff);
    Log.v("saved rate of ", cNm + " for " + title);
    int ledSpeed = 3000;
    int color = 0xFF02ffff;

    if (cNm.equals("500") || cNm.equals("3000")) {
        ledSpeed = Integer.parseInt(cNm);
        color = clr;
    }

    notification.setLights(color, ledSpeed, ledSpeed);

    if (Preferences.getInstance(applicationContext).getNotificationVibrateEnabled()) {
        notification.setVibrate(new long[] { 0, 250, 250, 250 });
    } else {
        notification.setVibrate(new long[] { 0 });
    }
    notification.setColor(0xFF546e7a);
    notification.setAutoCancel(true);
    notification.setStyle(new NotificationCompat.BigTextStyle().bigText(longText));

    Bitmap largeIconBitmap;
    try {
        largeIconBitmap = MediaStore.Images.Media.getBitmap(applicationContext.getContentResolver(),
                Uri.parse(Utils.getContactPhotoUri(applicationContext, contact)));
        largeIconBitmap = Bitmap.createScaledBitmap(largeIconBitmap, 256, 256, false);
        largeIconBitmap = Utils.applyCircularMask(largeIconBitmap);
        notification.setLargeIcon(largeIconBitmap);
    } catch (Exception ignored) {
        // Do nothing.
    }

    Intent intent = new Intent(applicationContext, ConversationActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra(applicationContext.getString(R.string.conversation_extra_contact), contact);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(applicationContext);
    stackBuilder.addParentStack(ConversationActivity.class);
    stackBuilder.addNextIntent(intent);
    notification.setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT));

    Intent replyIntent = new Intent(applicationContext, ConversationQuickReplyActivity.class);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        replyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
    } else {
        //noinspection deprecation
        replyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
    }
    replyIntent.putExtra(applicationContext.getString(R.string.conversation_extra_contact), contact);
    PendingIntent replyPendingIntent = PendingIntent.getActivity(applicationContext, 0, replyIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationCompat.Action.Builder replyAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_reply_white_24dp, applicationContext.getString(R.string.notifications_button_reply),
            replyPendingIntent);
    notification.addAction(replyAction.build());

    Intent markAsReadIntent = new Intent(applicationContext, MarkAsReadReceiver.class);
    markAsReadIntent.putExtra(applicationContext.getString(R.string.conversation_extra_contact), contact);
    PendingIntent markAsReadPendingIntent = PendingIntent.getBroadcast(applicationContext, 0, markAsReadIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationCompat.Action.Builder markAsReadAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_drafts_white_24dp,
            applicationContext.getString(R.string.notifications_button_mark_read), markAsReadPendingIntent);
    notification.addAction(markAsReadAction.build());

    int id;
    if (notificationIds.get(contact) != null) {
        id = notificationIds.get(contact);
    } else {
        id = notificationIdCount++;
        notificationIds.put(contact, id);
    }
    NotificationManager notificationManager = (NotificationManager) applicationContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(id, notification.build());
}

From source file:com.phonegap.customcamera.NativeCameraLauncher.java

public Bitmap scaleBitmap(Bitmap bitmap) {
    int newWidth = this.targetWidth;
    int newHeight = this.targetHeight;
    int origWidth = bitmap.getWidth();
    int origHeight = bitmap.getHeight();

    // If no new width or height were specified return the original bitmap
    if (newWidth <= 0 && newHeight <= 0) {
        return bitmap;
    }/*from www . j a  va 2 s  .  c  o m*/
    // Only the width was specified
    else if (newWidth > 0 && newHeight <= 0) {
        newHeight = (newWidth * origHeight) / origWidth;
    }
    // only the height was specified
    else if (newWidth <= 0 && newHeight > 0) {
        newWidth = (newHeight * origWidth) / origHeight;
    }
    // If the user specified both a positive width and height
    // (potentially different aspect ratio) then the width or height is
    // scaled so that the image fits while maintaining aspect ratio.
    // Alternatively, the specified width and height could have been
    // kept and Bitmap.SCALE_TO_FIT specified when scaling, but this
    // would result in whitespace in the new image.
    else {
        double newRatio = newWidth / (double) newHeight;
        double origRatio = origWidth / (double) origHeight;

        if (origRatio > newRatio) {
            newHeight = (newWidth * origHeight) / origWidth;
        } else if (origRatio < newRatio) {
            newWidth = (newHeight * origWidth) / origHeight;
        }
    }

    return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}

From source file:com.sourcey.materiallogindemo.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Permission StrictMode
    if (Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }/*from  ww  w  .j  a  v a  2 s  . co  m*/

    Bundle extras = getIntent().getExtras();
    // ?? null
    if (extras != null) {
        user_id = extras.getString("user_id");
        name = extras.getString("name");
        image = extras.getString("image");
    }

    txtStart = (AutoCompleteTextView) findViewById(R.id.txtStart);
    txtEnd = (AutoCompleteTextView) findViewById(R.id.txtEnd);
    txtAppoint = (AutoCompleteTextView) findViewById(R.id.txtAppoint);
    txtTime = (EditText) findViewById(R.id.txtTime);
    txtLicensePlate = (EditText) findViewById(R.id.txtLicensePlate);
    btnImageProfile = (ImageButton) findViewById(R.id.btnImageProfile);
    txtName = (TextView) findViewById(R.id.txtName);

    radioGroup = (RadioGroup) findViewById(R.id.radio);

    badge = (TextView) findViewById(R.id.badge);

    final Button btnSave = (Button) findViewById(R.id.btnSave);
    final Button btnCancel = (Button) findViewById(R.id.btnCancel);
    //final Button btnPost = (Button) findViewById(R.id.btnPost);
    final Button btnFeed = (Button) findViewById(R.id.btnFeed);
    final Button btnSearch = (Button) findViewById(R.id.btnSearch);
    final Button btnNotification = (Button) findViewById(R.id.btnNotification);
    final Button btnLogout = (Button) findViewById(R.id.btnLogout);
    final Button btnTime = (Button) findViewById(R.id.btnTime);
    final Button btnComment = (Button) findViewById(R.id.btnComment);
    // get the current time
    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    mHour = c.get(Calendar.HOUR);
    mMinute = c.get(Calendar.MINUTE);

    String url = getString(R.string.url) + "notification.php";
    notifications = master.GetCountNotification(user_id, url);
    if (notifications > 0) {
        badge.setVisibility(View.VISIBLE);
        badge.setText(String.valueOf(notifications));
    } else {
        badge.setVisibility(View.GONE);
    }

    // display the current time
    updateCurrentTime();
    LoadItems();
    //Create adapter
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, item);
    txtStart.setThreshold(1);
    //Set adapter to AutoCompleteTextView
    txtStart.setAdapter(adapter);
    txtStart.setOnItemSelectedListener(this);
    txtStart.setOnItemClickListener(this);

    //Set adapter to AutoCompleteTextView
    txtEnd.setAdapter(adapter);
    txtEnd.setOnItemSelectedListener(this);
    txtEnd.setOnItemClickListener(this);
    //Create adapter

    //Set adapter to AutoCompleteTextView
    txtAppoint.setAdapter(adapter);
    txtAppoint.setOnItemSelectedListener(this);
    txtAppoint.setOnItemClickListener(this);

    txtName.setText(name);
    String photo_url_str = getString(R.string.url_image)
            + (("".equals(image.trim()) || image == null) ? "no.png" : image.trim());
    URL newurl = null;
    try {
        newurl = new URL(photo_url_str);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    Bitmap b = null;
    try {
        b = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
    btnImageProfile.setImageBitmap(Bitmap.createScaledBitmap(b, 80, 80, false));

    btnSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogMap();
        }
    });

    btnTime.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(TIME_DIALOG_ID);
        }
    });
    btnSave.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            int selectedId = radioGroup.getCheckedRadioButtonId();

            // find the radiobutton by returned id
            type = ((RadioButton) findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();
            if ("".equals(type)) {
                type = "CAR";
            } else {
                type = "NOCAR";
            }
            /* Toast.makeText(getBaseContext(),
                type, Toast.LENGTH_SHORT).show();*/

            start = txtStart.getText().toString();
            end = txtEnd.getText().toString();
            meeting_point = txtAppoint.getText().toString();
            map_datetime = datePoint.trim();
            license_plate = txtLicensePlate.getText().toString();

            if ("".equals(start) || "".equals(end) || "".equals(meeting_point) || "".equals(map_datetime)
                    || "".equals(license_plate) || "".equals(txtTime.getText().toString().trim())) {
                MessageDialog("???");
            } else {
                String url = getString(R.string.url) + "save.php";
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("user_id", user_id));
                params.add(new BasicNameValuePair("start", start));
                params.add(new BasicNameValuePair("end", end));
                params.add(new BasicNameValuePair("meeting_point", meeting_point));
                params.add(new BasicNameValuePair("map_datetime", map_datetime));
                params.add(new BasicNameValuePair("license_plate", license_plate));
                params.add(new BasicNameValuePair("type", type));

                String resultServer = getHttpPost(url, params);

                JSONObject c;
                try {
                    c = new JSONObject(resultServer);
                    String status = c.getString("status");
                    MessageDialog(status);
                    if ("?".equals(status)) {
                        ClearData();
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    MessageDialog(e.getMessage());
                }
            }
        }
    });

    btnCancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            ClearData();
        }
    });

    /*        btnPost.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
       *//* Intent i = new Intent(getBaseContext(), PostItemActivity.class);
          i.putExtra("user_id", user_id);
          startActivity(i);*//*
                              // get selected radio button from radioGroup
                                      
                              }
                              });*/

    btnFeed.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            /*  if(!start.getText().toString().equals("") &&!end.getText().toString().equals("")&&
                !point.getText().toString().equals("")&&!time.getText().toString().equals("")&&!license.getText().toString().equals("")) {
            Intent newActivity = new Intent(MainActivity.this, commit.class);
            startActivity(newActivity);
              }*/
            Intent i = new Intent(getBaseContext(), PostItemActivity.class);
            i.putExtra("user_id", user_id);
            i.putExtra("name", name);
            i.putExtra("image", image);
            startActivity(i);
        }
    });
    btnNotification.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getBaseContext(), NotificationActivity.class);
            i.putExtra("user_id", user_id);
            i.putExtra("name", name);
            i.putExtra("image", image);
            startActivity(i);
        }
    });
    btnLogout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getBaseContext(), LoginActivity.class);
            startActivity(i);
        }
    });
    btnComment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getBaseContext(), CommentActivity.class);
            i.putExtra("user_id", user_id);
            i.putExtra("name", name);
            i.putExtra("image", image);
            startActivity(i);
        }
    });
    /*      final Button btn5 = (Button) findViewById(R.id.button3);
          btn5.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
    }
          });*/

    //RadioGroup car = (RadioGroup) this.findViewById ( R.id.textView18 );

    // car.check(R.id.radioButton);
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    //client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

From source file:com.adrguides.model.Guide.java

private void saveBitmapToFile(Context context, File f, URL imageURL) throws IOException {

    InputStream in = null;/*from   w  w w.  j  ava 2  s. c o  m*/
    OutputStream out = null;
    try {

        Bitmap newbmp;

        // read bitmap from source.
        in = HTTPUtils.openAddress(context, imageURL);
        Bitmap bmp = BitmapFactory.decodeStream(in);
        int w = bmp.getWidth();
        int h = bmp.getHeight();
        if (w > h) {
            newbmp = Bitmap.createBitmap(bmp, (w - h) / 2, 0, h, h);
        } else {
            newbmp = Bitmap.createBitmap(bmp, 0, (h - w) / 2, w, w);
        }
        if (newbmp != bmp) {
            bmp.recycle();
            bmp = newbmp;
        }

        float density = context.getResources().getDisplayMetrics().density;
        newbmp = Bitmap.createScaledBitmap(bmp, (int) (THUMBNAIL_WIDTH * density),
                (int) (THUMBNAIL_HEIGHT * density), true);
        if (newbmp != bmp) {
            bmp.recycle();
            bmp = newbmp;
        }

        // store in local filesystem.
        out = new FileOutputStream(f);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
        bmp.recycle();

    } finally {
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }
}

From source file:ca.ualberta.cs.cmput301w15t04team04project.FragmentEditItem2.java

/**
 * <b>This part of code is from:</b><br>
 * {@link http://stackoverflow.com/questions/4830711/how-to-convert-a-image-into-base64-string}<br>
 * @since March 26/*from w  w w .j av a 2s . c  o m*/
 */
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == -1) {

            Drawable drawable = Drawable.createFromPath(imageFileUri.getPath());
            Bitmap bitmap = BitmapFactory.decodeFile(imageFileUri.getPath());

            myActivity.setReceiptBitmap(bitmap, 1);

            ImageButton button = (ImageButton) thisview.findViewById(R.id.addRecieptImageButton);
            button.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 256, 256, false));

        }
    }

}

From source file:com.example.android.camera.CameraActivity.java

@Override
protected void onResume() {
    super.onResume();

    Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {

        @Override/*  w w w . j a v a2s .com*/
        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:com.eyekabob.EventInfo.java

private void handleImageResponse(Bitmap img) {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    float metWidth = metrics.widthPixels;
    float imgWidth = img.getWidth();
    float ratio = metWidth / imgWidth;
    // Add a little buffer room
    int newWidth = (int) Math.floor(img.getWidth() * ratio) - 50;
    int newHeight = (int) Math.floor(img.getHeight() * ratio) - 50;

    ImageView iv = (ImageView) findViewById(R.id.infoImageView);
    Bitmap rescaledImg = Bitmap.createScaledBitmap(img, newWidth, newHeight, false);
    iv.setImageBitmap(rescaledImg);//from   ww  w. ja v a2 s.c om
}

From source file:com.example.wojtekswiderski.woahpaper.GcmIntentService.java

public boolean setWallPaper(int start) {
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    int height = displayMetrics.heightPixels;
    int width = displayMetrics.widthPixels;

    String url = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=1&q=" + word + "&start="
            + start;/*from www .  ja  v  a 2  s  . co  m*/
    String imageUrl;
    try {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        JSONObject deliverable;

        try {
            deliverable = new JSONObject(response.toString());
            imageUrl = deliverable.getJSONObject("responseData").getJSONArray("results").getJSONObject(0)
                    .getString("url");
            Log.i(TAG, imageUrl);
            URL imageObj = new URL(imageUrl);

            Bitmap bmp = BitmapFactory.decodeStream(imageObj.openConnection().getInputStream());

            int x = bmp.getWidth();
            int y = bmp.getHeight();
            double ratioX = ((double) x) / ((double) width);
            double ratioY = ((double) y) / ((double) height);

            Log.i(TAG, "Width: " + width + " Height: " + height);
            Log.i(TAG, "X: " + x + " Y: " + y);
            Log.i(TAG, "RatioX: " + ratioX + " RatioY: " + ratioY);

            if (ratioX > ratioY) {
                bmp = Bitmap.createScaledBitmap(bmp, (int) (((double) x) / ratioY), height, false);
            } else {
                bmp = Bitmap.createScaledBitmap(bmp, width, (int) (((double) y) / ratioX), false);
            }

            Log.i(TAG, "newX: " + bmp.getWidth() + " newY: " + bmp.getHeight());

            Bitmap bmpBack = Bitmap.createBitmap(getWallpaperDesiredMinimumWidth(),
                    getWallpaperDesiredMinimumHeight(), Bitmap.Config.ARGB_8888);
            Bitmap bmOverlay = Bitmap.createBitmap(bmpBack.getWidth(), bmpBack.getHeight(),
                    bmpBack.getConfig());

            Canvas canvas = new Canvas(bmOverlay);
            canvas.drawBitmap(bmpBack, new Matrix(), null);
            canvas.drawBitmap(bmp, getWallpaperDesiredMinimumWidth() / 2 - bmp.getWidth() / 2, 0, null);

            WallpaperManager wpm = WallpaperManager.getInstance(this);
            wpm.setBitmap(bmOverlay);
        } catch (JSONException ex) {
            Log.e(TAG, "Could not convert to object");
            ex.printStackTrace();
            return true;
        }
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e(TAG, "Wrong url");
        return true;
    } catch (IOException ey) {
        ey.printStackTrace();
        Log.e(TAG, "Server down");
        return true;
    }
    return false;
}

From source file:com.android.volley.toolbox.ImageRequest.java

/**
 * The real guts of parseNetworkResponse. Broken out for readability.
 *///  www .j av a 2  s . co m
private Response<Bitmap> doParse(NetworkResponse response) {
    byte[] data = response.data;
    BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
    Bitmap bitmap = null;
    if (mMaxWidth == 0 && mMaxHeight == 0) {
        decodeOptions.inPreferredConfig = mDecodeConfig;
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
    } else {
        // If we have to resize this image, first get the natural bounds.
        decodeOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
        int actualWidth = decodeOptions.outWidth;
        int actualHeight = decodeOptions.outHeight;

        // Then compute the dimensions we would ideally like to decode to.
        int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight, actualWidth, actualHeight, mScaleType);
        int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth, actualHeight, actualWidth, mScaleType);

        // Decode to the nearest power of two scaling factor.
        decodeOptions.inJustDecodeBounds = false;
        // TODO(ficus): Do we need this or is it okay since API 8 doesn't support it?
        // decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED;
        decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
        Bitmap tempBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);

        // If necessary, scale down to the maximal acceptable size.
        if (tempBitmap != null
                && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) {
            bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true);
            tempBitmap.recycle();
        } else {
            bitmap = tempBitmap;
        }
    }

    if (bitmap == null) {
        return Response.error(new ParseError(response));
    } else {
        return Response.success(bitmap, HttpHeaderParser.parseCacheHeaders(response));
    }
}