Example usage for android.graphics Matrix Matrix

List of usage examples for android.graphics Matrix Matrix

Introduction

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

Prototype

public Matrix() 

Source Link

Document

Create an identity matrix

Usage

From source file:com.bilibili.boxing.utils.CameraPickerHelper.java

private boolean rotateSourceFile(File file) throws IOException {
    if (file == null || !file.exists()) {
        return false;
    }//from ww  w .  jav a  2  s  .  co m
    FileOutputStream outputStream = null;
    Bitmap bitmap = null;
    Bitmap outBitmap = null;
    try {
        int degree = BoxingExifHelper.getRotateDegree(file.getAbsolutePath());
        Matrix matrix = new Matrix();
        if (degree != 0) {
            matrix.postRotate(degree);
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
        outBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
        outputStream = new FileOutputStream(file);
        outBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        outputStream.flush();
        return true;
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                BoxingLog.d("IOException when output stream closing!");
            }
        }
        if (bitmap != null) {
            bitmap.recycle();
        }
        if (outBitmap != null) {
            outBitmap.recycle();
        }
    }
}

From source file:com.kabootar.GlassMemeGenerator.ImageOverlay.java

public static boolean saveToSD(final Bitmap overlaid, final String sdPath, final String fileName) {
    boolean isItSaved = false;
    new AsyncTask<Void, Void, Void>() {

        @Override//  w  w w  .j  ava 2s .  com
        protected Void doInBackground(Void... arg0) {

            File image = new File(sdPath, fileName);

            FileOutputStream outStream;
            try {

                outStream = new FileOutputStream(image);
                //resize image
                Bitmap newoverlaid = getResizedBitmap(overlaid, 1000, 1362);
                newoverlaid.compress(Bitmap.CompressFormat.PNG, 100, outStream);

                outStream.flush();
                outStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
            int width = bm.getWidth();
            int height = bm.getHeight();
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;
            // CREATE A MATRIX FOR THE MANIPULATION
            Matrix matrix = new Matrix();
            // RESIZE THE BIT MAP
            matrix.postScale(scaleWidth, scaleHeight);

            // "RECREATE" THE NEW BITMAP
            Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
            return resizedBitmap;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
        }
    }.execute();

    return isItSaved;
}

From source file:com.appsimobile.appsii.module.weather.WeatherLoadingService.java

/**
 * Downloads the header images for the given woeid and weather-data. Failure is considered
 * non-fatal./*from w ww. j a  v  a  2 s  .com*/
 *
 * @throws VolleyError
 */
public static void downloadWeatherImages(Context context, BitmapUtils bitmapUtils, String woeid,
        WeatherData weatherData, String timezone) throws VolleyError {

    WindowManager windowManager = AppInjector.provideWindowManager();

    // first we need to determine if it is day or night.
    // TODO: this needs the timezone

    if (timezone == null) {
        timezone = TimeZone.getDefault().getID();
    }

    WeatherUtils weatherUtils = AppInjector.provideWeatherUtils();
    boolean isDay = weatherUtils.isDay(timezone, weatherData);
    ImageDownloadHelper downloadHelper = ImageDownloadHelper.getInstance(context);

    // call into the download-helper this will return a json object with
    // city photos matching the current weather condition.
    JSONObject photos = downloadHelper.searchCityWeatherPhotos(woeid, weatherData.nowConditionCode, isDay);

    // Now we need the screen dimension to know which photos have a usable size.
    int dimen = getMaxScreenDimension(windowManager);

    // determine the photos that can be used.
    List<ImageDownloadHelper.PhotoInfo> result = new ArrayList<>();
    ImageDownloadHelper.getEligiblePhotosFromResponse(photos, result, dimen);

    // when no usable photos have been found try photos at the city level with
    // no weather condition info.
    if (result.isEmpty()) {
        photos = downloadHelper.searchCityImage(woeid);
        ImageDownloadHelper.getEligiblePhotosFromResponse(photos, result, dimen);
        // when still no photo was found, clear the existing photos and return
        if (result.isEmpty()) {
            weatherUtils.clearCityPhotos(context, woeid, 0);
            return;
        }
    }

    // Now determine the amount of photos we should download
    int N = Math.min(MAX_PHOTO_COUNT, result.size());
    // idx keeps the index of the actually downloaded photo count
    int idx = 0;
    // note the idx < N instead of i < N.
    // this loop must continue until the amount is satisfied.
    for (int i = 0; idx < N; i++) {
        // quit when the end of the list is reached
        if (i >= result.size())
            break;

        // try to download the photo details from the webservice.
        ImageDownloadHelper.PhotoInfo info = result.get(i);
        JSONObject photoInfo = downloadHelper.loadPhotoInfo(context, info.id);
        if (photoInfo != null) {

            // we need to know if the photo is rotated. If so, we need to apply this
            // rotation after download.
            int rotation = ImageDownloadHelper.getRotationFromJson(photoInfo);
            if (downloadFile(context, info, woeid, idx)) {
                // Apply rotation when non zero
                if (rotation != 0) {
                    File cacheDir = weatherUtils.getWeatherPhotoCacheDir(context);
                    String fileName = weatherUtils.createPhotoFileName(woeid, idx);
                    File photoImage = new File(cacheDir, fileName);
                    Bitmap bitmap = bitmapUtils.decodeSampledBitmapFromFile(photoImage, dimen, dimen);
                    if (bitmap == null) {
                        Log.wtf("WeatherLoadingService", "error decoding bitmap");
                        continue;
                    }

                    Matrix matrix = new Matrix();
                    matrix.postRotate(rotation);
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix,
                            false);
                    weatherUtils.saveBitmap(context, bitmap, woeid, idx);
                }
                // success, handle the next one.
                idx++;
            }
        }
    }
    // remove photos at higher indexes than the amount downloaded.
    weatherUtils.clearCityPhotos(context, woeid, idx + 1);

}

From source file:ir.rasen.charsoo.controller.image_loader.core.decode.BaseImageDecoder.java

protected Bitmap considerExactScaleAndOrientatiton(Bitmap subsampledBitmap, ImageDecodingInfo decodingInfo,
        int rotation, boolean flipHorizontal) {
    Matrix m = new Matrix();
    // Scale to exact size if need
    ImageScaleType scaleType = decodingInfo.getImageScaleType();
    if (scaleType == ImageScaleType.EXACTLY || scaleType == ImageScaleType.EXACTLY_STRETCHED) {
        ImageSize srcSize = new ImageSize(subsampledBitmap.getWidth(), subsampledBitmap.getHeight(), rotation);
        float scale = ImageSizeUtils.computeImageScale(srcSize, decodingInfo.getTargetSize(),
                decodingInfo.getViewScaleType(), scaleType == ImageScaleType.EXACTLY_STRETCHED);
        if (Float.compare(scale, 1f) != 0) {
            m.setScale(scale, scale);/* w  ww  .j a  v a  2s.  com*/

            if (loggingEnabled) {
                L.d(LOG_SCALE_IMAGE, srcSize, srcSize.scale(scale), scale, decodingInfo.getImageKey());
            }
        }
    }
    // Flip bitmap if need
    if (flipHorizontal) {
        m.postScale(-1, 1);

        if (loggingEnabled)
            L.d(LOG_FLIP_IMAGE, decodingInfo.getImageKey());
    }
    // Rotate bitmap if need
    if (rotation != 0) {
        m.postRotate(rotation);

        if (loggingEnabled)
            L.d(LOG_ROTATE_IMAGE, rotation, decodingInfo.getImageKey());
    }

    Bitmap finalBitmap = Bitmap.createBitmap(subsampledBitmap, 0, 0, subsampledBitmap.getWidth(),
            subsampledBitmap.getHeight(), m, true);
    if (finalBitmap != subsampledBitmap) {
        subsampledBitmap.recycle();
    }
    return finalBitmap;
}

From source file:com.benefit.buy.library.http.query.callback.BitmapAjaxCallback.java

private static Matrix getRotateMatrix(int ori) {
    Matrix matrix = new Matrix();
    switch (ori) {
    case 2:// www  .  java2 s .  co  m
        matrix.setScale(-1, 1);
        break;
    case 3:
        matrix.setRotate(180);
        break;
    case 4:
        matrix.setRotate(180);
        matrix.postScale(-1, 1);
        break;
    case 5:
        matrix.setRotate(90);
        matrix.postScale(-1, 1);
        break;
    case 6:
        matrix.setRotate(90);
        break;
    case 7:
        matrix.setRotate(-90);
        matrix.postScale(-1, 1);
        break;
    case 8:
        matrix.setRotate(-90);
        break;
    }
    return matrix;
}

From source file:com.plugin.camera.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits.//from  w w w.j  a va2  s .  co  m
 *
 * @param requestCode
 *            The request code originally supplied to
 *            startActivityForResult(), allowing you to identify who this
 *            result came from.
 * @param resultCode
 *            The integer result code returned by the child activity through
 *            its setResult().
 * @param intent
 *            An Intent, which can return result data to the caller (various
 *            data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // If image available
    if (resultCode == Activity.RESULT_OK) {
        try {
            // Create an ExifHelper to save the exif data that is lost
            // during compression
            ExifHelper exif = new ExifHelper();
            exif.createInFile(
                    getTempDirectoryPath(this.cordova.getActivity().getApplicationContext()) + "/Pic.jpg");
            exif.readExifData();

            // Read in bitmap of captured image
            Bitmap bitmap;
            try {
                bitmap = android.provider.MediaStore.Images.Media
                        .getBitmap(this.cordova.getActivity().getContentResolver(), imageUri);
            } catch (FileNotFoundException e) {
                Uri uri = intent.getData();
                android.content.ContentResolver resolver = this.cordova.getActivity().getContentResolver();
                bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
            }

            bitmap = scaleBitmap(bitmap);

            // Create entry in media store for image
            // (Don't use insertImage() because it uses default compression
            // setting of 50 - no way to change it)
            ContentValues values = new ContentValues();
            values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = null;
            try {
                uri = this.cordova.getActivity().getContentResolver()
                        .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } catch (UnsupportedOperationException e) {
                LOG.d(LOG_TAG, "Can't write to external media storage.");
                try {
                    uri = this.cordova.getActivity().getContentResolver()
                            .insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                } catch (UnsupportedOperationException ex) {
                    LOG.d(LOG_TAG, "Can't write to internal media storage.");
                    this.failPicture("Error capturing image - no media storage found.");
                    return;
                }
            }
            //This if block is added to the plugin to solve the issue which was saving portrait images in landscape with -90 degree rotetion
            if (intent.getBooleanExtra("portrait", false)) {
                Matrix matrix = new Matrix();
                matrix.preRotate(90);
                try {
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix,
                            true);
                } catch (Exception e) {
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth() / 2, bitmap.getHeight() / 2,
                            matrix, true);
                    e.printStackTrace();
                }
            }

            // Add compressed version of captured image to returned media
            // store Uri
            OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            exif.createOutFile(getRealPathFromURI(uri, this.cordova));
            exif.writeExifData();

            // Send Uri back to JavaScript for viewing image
            this.callbackContext.success(getRealPathFromURI(uri, this.cordova));

            bitmap.recycle();
            bitmap = null;
            System.gc();

            checkForDuplicateImage();
        } catch (IOException e) {
            e.printStackTrace();
            this.failPicture("Error capturing image.");
        }
    }

    // If cancelled
    else if (resultCode == Activity.RESULT_CANCELED) {
        this.failPicture("Camera cancelled.");
    }

    // If something else
    else {
        this.failPicture("Did not complete!");
    }
}

From source file:com.android.gallery3d.filtershow.imageshow.ImageShow.java

/**
 * This function calculates a Image to Screen Transformation matrix
 *
 * @param reflectRotation set true if you want the rotation encoded
 * @return Image to Screen transformation matrix
 *///from w  ww .j  av  a  2  s. co m
protected Matrix getImageToScreenMatrix(boolean reflectRotation) {
    MasterImage master = MasterImage.getImage();
    if (master.getOriginalBounds() == null) {
        return new Matrix();
    }
    Matrix m = GeometryMathUtils.getImageToScreenMatrix(master.getPreset().getGeometryFilters(),
            reflectRotation, master.getOriginalBounds(), getWidth(), getHeight());
    Point translate = master.getTranslation();
    float scaleFactor = master.getScaleFactor();
    m.postTranslate(translate.x, translate.y);
    m.postScale(scaleFactor, scaleFactor, getWidth() / 2.0f, getHeight() / 2.0f);
    return m;
}

From source file:com.appbase.androidquery.callback.BitmapAjaxCallback.java

private static Matrix getRotateMatrix(int ori) {

    Matrix matrix = new Matrix();
    switch (ori) {
    case 2://from  w ww  .j  a  va  2s.  c om
        matrix.setScale(-1, 1);
        break;
    case 3:
        matrix.setRotate(180);
        break;
    case 4:
        matrix.setRotate(180);
        matrix.postScale(-1, 1);
        break;
    case 5:
        matrix.setRotate(90);
        matrix.postScale(-1, 1);
        break;
    case 6:
        matrix.setRotate(90);
        break;
    case 7:
        matrix.setRotate(-90);
        matrix.postScale(-1, 1);
        break;
    case 8:
        matrix.setRotate(-90);
        break;

    }

    return matrix;

}

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;/*  ww  w.  jav a  2  s .c  o  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.example.google.maps.dataviz.MainActivity.java

private void addDataToMap() {
    ArrayList<LatLng> coords = new ArrayList<LatLng>();
    ArrayList<Double> samples = new ArrayList<Double>();
    double minElevation = Integer.MAX_VALUE;
    double maxElevation = Integer.MIN_VALUE;

    try {//w  w w  .  j a va 2s. com
        Resources res = getResources();
        InputStream istream = res.openRawResource(R.raw.elevation);
        byte[] buff = new byte[istream.available()];
        istream.read(buff);
        istream.close();

        String json = new String(buff);
        JSONArray jsonArray = new JSONArray(json);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject sample = jsonArray.getJSONObject(i);

            double elevation = sample.getDouble("elevation");
            minElevation = elevation < minElevation ? elevation : minElevation;
            maxElevation = elevation > maxElevation ? elevation : maxElevation;

            JSONObject location = sample.getJSONObject("location");
            LatLng position = new LatLng(location.getDouble("lat"), location.getDouble("lng"));

            coords.add(position);
            samples.add(elevation);
        }
    } catch (IOException e) {
        Log.e(this.getClass().getName(), "Error accessing elevation data file.");
        return;
    } catch (JSONException e) {
        Log.e(this.getClass().getName(), "Error processing elevation data (JSON).");
        return;
    }

    for (int i = 0; i < coords.size(); i++) {
        double elevation = samples.get(i);
        int height = (int) (elevation / maxElevation * MARKER_HEIGHT);

        Bitmap.Config conf = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = Bitmap.createBitmap(MARKER_WIDTH, height, conf);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawPaint(mPaint);

        // Invert the bitmap (top red, bottom blue).
        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);

        LatLng position = coords.get(i);
        BitmapDescriptor bitmapDesc = BitmapDescriptorFactory.fromBitmap(bitmap);
        mMap.addMarker(new MarkerOptions().position(position).icon(bitmapDesc).alpha(.8f)
                .title(new DecimalFormat("#.## meters").format(elevation)));
    }
}