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.ruesga.rview.misc.PicassoHelper.java

private static void loadWithFallbackUrls(final Context context, final Picasso picasso, final Object into,
        final Drawable placeholder, final List<String> urls) {
    final String nextUrl;
    synchronized (urls) {
        nextUrl = urls.isEmpty() ? null : urls.get(0);
    }/*from www  .ja  v  a 2  s.com*/

    final Target target = new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
            sTargets.remove(this);

            synchronized (urls) {
                urls.clear();
                urls.add(nextUrl);
            }

            BitmapDrawable dw = new BitmapDrawable(context.getResources(), bitmap);
            drawInto(dw);
        }

        @Override
        public void onBitmapFailed(Drawable drawable) {
            sTargets.remove(this);

            // Next url
            synchronized (urls) {
                if (urls.contains(nextUrl)) {
                    urls.remove(nextUrl);
                }
            }
            loadWithFallbackUrls(context, picasso, into, placeholder, urls);
        }

        @Override
        public void onPrepareLoad(Drawable drawable) {
            drawInto(drawable);
        }

        private void drawInto(Drawable dw) {
            if (into instanceof ImageView) {
                ((ImageView) into).setImageDrawable(dw);

            } else if (into instanceof MenuItem) {
                // Resize to fit into menu icon
                int size = context.getResources()
                        .getDimensionPixelSize(com.ruesga.rview.drawer.R.dimen.drawer_navigation_icon_size);
                Bitmap resized = Bitmap.createScaledBitmap(BitmapUtils.convertToBitmap(dw), size, size, false);
                Drawable icon = new BitmapDrawable(context.getResources(), resized);
                dw.setBounds(0, 0, size, size);
                ((MenuItem) into).setIcon(icon);
            }
        }
    };
    sTargets.add(target);

    if (nextUrl != null) {
        picasso.load(nextUrl).placeholder(placeholder).transform(new CircleTransform()).into(target);
    } else {
        // Placeholder
        target.onPrepareLoad(placeholder);
    }
}

From source file:com.example.d062654.faciliman._3f_FacilityDetailed.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ll = (RelativeLayout) inflater.inflate(R.layout.facilitydetailed, container, false);
    facarchive = (Button) ll.findViewById(R.id.facarchive);

    factitle = (TextView) ll.findViewById(R.id.factitle);
    factitle.setText(incident.getTitle());
    facplace = (TextView) ll.findViewById(R.id.facplace);
    facplace.setText(incident.getLocation());
    facdetailed_location = (TextView) ll.findViewById(R.id.facdetailed_location);
    facdetailed_location.setText(incident.getExactLocation());
    facdetailed_description = (TextView) ll.findViewById(R.id.facdetailed_description);
    facdetailed_description.setText("Lampe Kaputt");
    facimage = (ImageView) ll.findViewById(R.id.facimage);
    facarchive.setOnClickListener(new View.OnClickListener() {
        @Override/*from w w w .  j a v  a  2s .c  o m*/
        public void onClick(View view) {
            Call<ResponseBody> call = Connection.getApiInterface().archieveIncident(user, incident.getId());
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.isSuccessful()) {
                        Toast.makeText(fragact.getApplicationContext(), "Archivierungsvorgang abgeschlossen",
                                Toast.LENGTH_SHORT).show();
                        facarchive.setEnabled(false);
                    } else if (response.code() == 401) {
                        // Handle unauthorized
                        Toast.makeText(fragact.getApplicationContext(), "Sorry! Failed to capture image",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        // Handle other responses
                        Toast.makeText(fragact.getApplicationContext(), "Sorry! Failed to capture image",
                                Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });

        }
    });

    Call<ResponseBody> call = Connection.getApiInterface().getFile(user, incident.getId());
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                // Do awesome stuff
                Bitmap bmp = null;

                try {
                    byte[] imgbytes = response.body().bytes();
                    int targetW = facimage.getWidth();
                    int targetH = facimage.getHeight();
                    // bimatp factory
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;

                    bmp = BitmapFactory.decodeByteArray(imgbytes, 0, imgbytes.length, options);

                    int photoW = options.outWidth;
                    int photoH = options.outHeight;
                    int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
                    options.inJustDecodeBounds = false;
                    options.inSampleSize = scaleFactor;
                    options.inPurgeable = true;

                    bmp = BitmapFactory.decodeByteArray(imgbytes, 0, imgbytes.length, options);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ImageView image = (ImageView) ll.findViewById(R.id.facimage);

                Matrix matrix = new Matrix();

                matrix.postRotate(90);

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(bmp, bmp.getWidth(), bmp.getHeight(), true);

                Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(),
                        scaledBitmap.getHeight(), matrix, true);
                facimage.setImageBitmap(rotatedBitmap);

            } else if (response.code() == 401) {
                // Handle unauthorized
                Toast.makeText(fragact.getApplicationContext(), "Sorry! Failed to capture image",
                        Toast.LENGTH_SHORT).show();
            } else {
                // Handle other responses
                Toast.makeText(fragact.getApplicationContext(), "Sorry! Failed to capture image",
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            // Log error here since request failed
            Log.e(TAG, t.toString());

        }
    });
    // Inflate the layout for this fragment
    return ll;
}

From source file:com.gmail.altakey.lucene.AsyncImageLoader.java

private Bitmap scale(Bitmap src) {
    int width = src.getWidth();
    int height = src.getHeight();
    final int maxWidth = this.view.getAcceleration().getMaximumBitmapWidth();
    final int maxHeight = this.view.getAcceleration().getMaximumBitmapHeight();
    if (maxWidth < 0 || maxHeight < 0)
        return src;
    if (width < maxWidth && height < maxHeight)
        return src;

    if (width > height) {
        height = (int) (height * (maxWidth / (float) width));
        width = maxWidth;/*from w  w  w  .j  a v a2 s.  c om*/
    }
    if (width < height) {
        width = (int) (width * (maxHeight / (float) height));
        height = maxHeight;
    }
    Log.d("AIL",
            String.format("scaling: (%d, %d) -> (%d, %d)", src.getWidth(), src.getHeight(), width, height));
    return Bitmap.createScaledBitmap(src, width, height, true);
}

From source file:eu.liveandgov.ar.core.ARViewFragment.java

/** Create MetaioSDK, handler for startCamera, ScreenshotCapture for IBS*  */
@Override//w  ww  .j a v a2  s  .c  o m
public void onCreate(Bundle savedInstanceState) {
    deb("ARViewFragment", "onCreate ARViewFragment");

    super.onCreate(savedInstanceState);

    metaioSDK = null;
    mGLSurfaceView = null;
    mRendererInitialized = false;

    ctxL = getTheContext();

    // ----------- Asynchronous start stop camera -----------------------
    handlerCamera = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.arg1 == 1)
                startCamera();
            super.handleMessage(msg);
        }
    };

    try {
        mSensors = new SensorsComponentAndroid(ctxL);

        metaioSDK = MetaioSDK.CreateMetaioSDKAndroid(ctxL,
                getResources().getString(R.string.metaioSDKSignature));
        metaioSDK.registerSensorsComponent(mSensors);
        mSensors.start(SensorsComponentAndroid.SENSOR_ALL);

        metaioSDK.registerCallback(new IMetaioSDKCallback() {

            /* (non-Javadoc)
             * @see com.metaio.sdk.jni.IMetaioSDKCallback#onTrackingEvent(com.metaio.sdk.jni.TrackingValuesVector)
             */
            @Override
            public void onTrackingEvent(TrackingValuesVector trackingValues) {
                //for (int i=0; i<trackingValues.size(); i++){
                if (trackingValues.get(0).getState() == com.metaio.sdk.jni.ETRACKING_STATE.ETS_LOST) {
                    ctxL.sendBroadcast(
                            new Intent("android.intent.action.MAIN").putExtra("ImageLost", "confirm"));
                } else if (trackingValues.get(0).getState() == com.metaio.sdk.jni.ETRACKING_STATE.ETS_FOUND) {
                    ctxL.sendBroadcast(new Intent("android.intent.action.MAIN").putExtra("ImageFound",
                            trackingValues.get(0).getCosName()));
                }
                //}

                super.onTrackingEvent(trackingValues);
            }

            @Override
            public void onSDKReady() {
                super.onSDKReady();
                // ----------- Asynchronous start camera -----------------------
                Message msg = new Message();
                msg.arg1 = 1;
                handlerCamera.sendMessage(msg);
            }

            /* (non-Javadoc)
             * @see com.metaio.sdk.jni.IMetaioSDKCallback#onCameraImageSaved(java.lang.String)
             */
            @Override
            public void onScreenshotSaved(String filepath) {

                try {
                    // convert to 4:3 ratio or 3:4. Otherwise service not working at all!
                    FileInputStream streamIn;
                    streamIn = new FileInputStream(filepath);
                    Bitmap bitmap = BitmapFactory.decodeStream(streamIn);

                    int w, h;
                    if (bitmap.getHeight() > bitmap.getWidth()) {
                        h = 640;
                        w = 480;
                    } else {
                        w = 640;
                        h = 480;
                    }
                    bitmap = Bitmap.createScaledBitmap(bitmap, w, h, false);

                    FileOutputStream out = new FileOutputStream(filepath);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 95, out);
                    out.close();
                    // Recognize now
                    new AsyncTask_ImRec(filepath, "5", ctxL).execute();
                } catch (Exception e) {

                }

            };
        });
    } catch (Exception e) {
        Log.e("CARF", "ARViewActivity.onCreate: failed to create or intialize metaio SDK: " + e.getMessage());
    }
}

From source file:com.atwal.wakeup.battery.util.Utilities.java

/**
 * remove bitmap white around white section by miao
 *///ww w  .jav a2 s  . c o m
public static Bitmap removeAroundWhiteSection(Bitmap icon) {
    int xStart = 0;
    int xEnd = 0;
    int yStart = 0;
    int yEnd = 0;
    int width = icon.getWidth();
    int height = icon.getHeight();
    Bitmap copyIcon = icon.copy(Bitmap.Config.ARGB_8888, false);
    copyIcon = Bitmap.createScaledBitmap(copyIcon, width, 1, false);
    for (int i = 0; i < width; i++) {
        int rgb = copyIcon.getPixel(i, 0);
        if (rgb != 0 && xStart == 0) {
            xStart = i;
            continue;
        }
        if (rgb == 0 && xStart != 0) {
            xEnd = i;
        }
    }

    copyIcon = icon.copy(Bitmap.Config.ARGB_8888, false);
    copyIcon = Bitmap.createScaledBitmap(copyIcon, 1, height, false);
    for (int i = 0; i < height; i++) {
        int rgb = copyIcon.getPixel(0, i);
        if (rgb != 0 && yStart == 0) {
            yStart = i;
            continue;
        }
        if (rgb == 0 && yStart != 0) {
            yEnd = i;
        }
    }
    if (xStart < xEnd && yStart < yEnd) {
        icon = Bitmap.createBitmap(icon, xStart, yStart, xEnd - xStart, yEnd - yStart);
        Log.d(TAG, "success remove white section");
    } else {
        Log.d(TAG, "fail remove white section");
    }
    return icon;
}

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

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.e("Check", "ActivityResult");
    Bitmap image = null;//w  w w. ja v a  2s  .co  m
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            image = (Bitmap) data.getExtras().get("data");
            image = Bitmap.createScaledBitmap(image, 100, 100, true);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.PNG, 100, bytes);

            byte[] objects = bytes.toByteArray();

            encodedmessage = Base64.encodeToString(objects, Base64.DEFAULT);
            imageView.setImageBitmap(image);
        }
    }
}

From source file:jahirfiquitiva.iconshowcase.tasks.ApplyWallpaper.java

private Bitmap scaleToActualAspectRatio(Bitmap bitmap) {
    if (bitmap != null) {
        boolean flag = true;

        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        int deviceWidth = displayMetrics.widthPixels;
        int deviceHeight = displayMetrics.heightPixels;

        int bitmapHeight = bitmap.getHeight();
        int bitmapWidth = bitmap.getWidth();
        if (bitmapWidth > deviceWidth) {
            flag = false;/* www.  j a v  a2  s  .  com*/
            int scaledHeight = deviceHeight;
            int scaledWidth = (scaledHeight * bitmapWidth) / bitmapHeight;
            try {
                if (scaledHeight > deviceHeight) {
                    scaledHeight = deviceHeight;
                }
                bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (flag) {
            if (bitmapHeight > deviceHeight) {
                int scaledWidth = (deviceHeight * bitmapWidth) / bitmapHeight;
                try {
                    if (scaledWidth > deviceWidth)
                        scaledWidth = deviceWidth;
                    bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, deviceHeight, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return bitmap;
}

From source file:org.chromium.chrome.browser.history.HistoryItemView.java

@Override
public void onLargeIconAvailable(Bitmap icon, int fallbackColor, boolean isFallbackColorDefault) {
    // TODO(twellington): move this somewhere that can be shared with bookmarks.
    if (icon == null) {
        mIconGenerator.setBackgroundColor(fallbackColor);
        icon = mIconGenerator.generateIconForUrl(getItem().getUrl());
        mIconImageView.setImageDrawable(new BitmapDrawable(getResources(), icon));
    } else {/* ww w .  j  ava  2 s .  com*/
        RoundedBitmapDrawable roundedIcon = RoundedBitmapDrawableFactory.create(getResources(),
                Bitmap.createScaledBitmap(icon, mDisplayedIconSize, mDisplayedIconSize, false));
        roundedIcon.setCornerRadius(mCornerRadius);
        mIconImageView.setImageDrawable(roundedIcon);
    }
}

From source file:menion.android.whereyougo.gui.activity.MainActivity.java

public static void setBitmapToImageView(Bitmap i, ImageView iv) {
    Logger.w(TAG, "setBitmapToImageView(), " + i.getWidth() + " x " + i.getHeight());
    if (Preferences.APPEARANCE_IMAGE_STRETCH) {
        int newWidth = Const.SCREEN_WIDTH;
        int newHeight = i.getHeight() * newWidth / i.getWidth();
        i = Bitmap.createScaledBitmap(i, newWidth, newHeight, false);
    }//w  w  w  .ja v a  2 s .  c o  m
    iv.setImageBitmap(i);
}

From source file:com.krayzk9s.imgurholo.services.UploadService.java

private static Bitmap lessResolution(String filePath, int width, int height) {
    BitmapFactory.Options options = new BitmapFactory.Options();

    // First decode with inJustDecodeBounds=true to check dimensions
    options.inPurgeable = true;//  w  ww .j a v  a  2 s .c o m
    options.inInputShareable = true;
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, width, height);
    BitmapFactory.decodeFile(filePath, options);
    float factor = calculateFactor(options, width, height);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    return Bitmap.createScaledBitmap(BitmapFactory.decodeFile(filePath, options),
            (int) Math.floor(options.outWidth * factor), (int) Math.floor(options.outHeight * factor), false);
}