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:net.kourlas.voipms_sms.Notifications.java

public void showNotifications(List<String> contacts) {
    if (!(ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationsActivity)) {
        Conversation[] conversations = Database.getInstance(applicationContext)
                .getConversations(preferences.getDid());
        for (Conversation conversation : conversations) {
            if (!conversation.isUnread() || !contacts.contains(conversation.getContact())
                    || (ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationActivity
                            && ((ConversationActivity) ActivityMonitor.getInstance().getCurrentActivity())
                                    .getContact().equals(conversation.getContact()))) {
                continue;
            }//from ww w. j a  v  a 2 s. c  o m

            String smsContact = Utils.getContactName(applicationContext, conversation.getContact());
            if (smsContact == null) {
                smsContact = Utils.getFormattedPhoneNumber(conversation.getContact());
            }

            String allSmses = "";
            String mostRecentSms = "";
            boolean initial = true;
            for (Message message : conversation.getMessages()) {
                if (message.getType() == Message.Type.INCOMING && message.isUnread()) {
                    if (initial) {
                        allSmses = message.getText();
                        mostRecentSms = message.getText();
                        initial = false;
                    } else {
                        allSmses = message.getText() + "\n" + allSmses;
                    }
                } else {
                    break;
                }
            }

            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(applicationContext);

            notificationBuilder.setContentTitle(smsContact);
            notificationBuilder.setContentText(mostRecentSms);
            notificationBuilder.setSmallIcon(R.drawable.ic_chat_white_24dp);
            notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
            notificationBuilder
                    .setSound(Uri.parse(Preferences.getInstance(applicationContext).getNotificationSound()));
            notificationBuilder.setLights(0xFFAA0000, 1000, 5000);
            if (Preferences.getInstance(applicationContext).getNotificationVibrateEnabled()) {
                notificationBuilder.setVibrate(new long[] { 0, 250, 250, 250 });
            } else {
                notificationBuilder.setVibrate(new long[] { 0 });
            }
            notificationBuilder.setColor(0xFFAA0000);
            notificationBuilder.setAutoCancel(true);
            notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(allSmses));

            Bitmap largeIconBitmap;
            try {
                largeIconBitmap = MediaStore.Images.Media.getBitmap(applicationContext.getContentResolver(),
                        Uri.parse(Utils.getContactPhotoUri(applicationContext, conversation.getContact())));
                largeIconBitmap = Bitmap.createScaledBitmap(largeIconBitmap, 256, 256, false);
                largeIconBitmap = Utils.applyCircularMask(largeIconBitmap);
                notificationBuilder.setLargeIcon(largeIconBitmap);
            } catch (Exception ignored) {

            }

            Intent intent = new Intent(applicationContext, ConversationActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(applicationContext);
            stackBuilder.addParentStack(ConversationActivity.class);
            stackBuilder.addNextIntent(intent);
            notificationBuilder
                    .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),
                    conversation.getContact());
            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);
            notificationBuilder.addAction(replyAction.build());

            Intent markAsReadIntent = new Intent(applicationContext, MarkAsReadReceiver.class);
            markAsReadIntent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            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);
            notificationBuilder.addAction(markAsReadAction.build());

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

From source file:br.ufrgs.ufrgsmapas.views.BuildingClusterRenderer.java

private static BitmapDescriptor scaleDown(Context context, int res) {

    BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(context, res);
    Bitmap bitmap = bitmapDrawable.getBitmap();
    int iconSizePx = MeasureUtils.convertDpToPixel(ICON_SIZE_DP, context);

    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, iconSizePx, iconSizePx, true);

    return BitmapDescriptorFactory.fromBitmap(scaledBitmap);
}

From source file:org.alpine_toolkit.AlpineToolkitService.java

private Notification build_notification() {
    Intent notification_intent = new Intent(this, AlpineToolkitActivity.class);
    // notification_intent.setAction(Constants.ACTION.MAIN);
    // notification_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pending_intent = PendingIntent.getActivity(this, 0, notification_intent, 0);

    Intent stop_intent = new Intent(this, AlpineToolkitService.class);
    stop_intent.setAction(STOP_ACTION);/*from w w  w  . ja  v a  2s .c  o  m*/
    PendingIntent pending_stop_intent = PendingIntent.getService(this, 0, stop_intent, 0);

    int icon_id = getResources().getIdentifier("icon", "drawable", getPackageName());
    int icon_transparent_id = getResources().getIdentifier("icon_transparent", "drawable", getPackageName());
    Bitmap icon = BitmapFactory.decodeResource(getResources(), icon_id);

    // return new NotificationCompat.Builder(this)
    return new Notification.Builder(this).setPriority(Notification.PRIORITY_MAX)
            .setContentTitle("Alpine Toolkit Service").setTicker("Alpine Toolkit Service is started") // Set the text that is displayed in the status bar when the notification first arrives.
            .setContentText("Hello!").setSmallIcon(icon_transparent_id)
            .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false)).setContentIntent(pending_intent) // Supply a PendingIntent to send when the notification is clicked.
            .setOngoing(true) //  Ongoing notifications cannot be dismissed by the user
            .addAction(android.R.drawable.ic_media_pause, "Stop", pending_stop_intent) // ic_media_stop
            .build();
}

From source file:com.luyaozhou.recognizethisforglass.ViewFinder.java

private void processPictureWhenReady(final String picturePath) {
    final File pictureFile = new File(picturePath);
    //Map<String, String > result = new HashMap<String,String>();

    if (pictureFile.exists()) {
        // The picture is ready; process it.
        Bitmap imageBitmap = null;/*w w w. j  ava  2s .co  m*/
        try {
            //               Bundle extras = data.getExtras();
            //               imageBitmap = (Bitmap) extras.get("data");
            FileInputStream fis = new FileInputStream(picturePath); //get the bitmap from file
            imageBitmap = (Bitmap) BitmapFactory.decodeStream(fis);

            if (imageBitmap != null) {
                Bitmap lScaledBitmap = Bitmap.createScaledBitmap(imageBitmap, 1600, 1200, false);
                if (lScaledBitmap != null) {
                    imageBitmap.recycle();
                    imageBitmap = null;

                    ByteArrayOutputStream lImageBytes = new ByteArrayOutputStream();
                    lScaledBitmap.compress(Bitmap.CompressFormat.JPEG, 30, lImageBytes);
                    lScaledBitmap.recycle();
                    lScaledBitmap = null;

                    byte[] lImageByteArray = lImageBytes.toByteArray();

                    HashMap<String, String> lValuePairs = new HashMap<String, String>();
                    lValuePairs.put("base64Image", Base64.encodeToString(lImageByteArray, Base64.DEFAULT));
                    lValuePairs.put("compressionLevel", "30");
                    lValuePairs.put("documentIdentifier", "DRIVER_LICENSE_CA");
                    lValuePairs.put("documentHints", "");
                    lValuePairs.put("dataReturnLevel", "15");
                    lValuePairs.put("returnImageType", "1");
                    lValuePairs.put("rotateImage", "0");
                    lValuePairs.put("data1", "");
                    lValuePairs.put("data2", "");
                    lValuePairs.put("data3", "");
                    lValuePairs.put("data4", "");
                    lValuePairs.put("data5", "");
                    lValuePairs.put("userName", "zbroyan@miteksystems.com");
                    lValuePairs.put("password", "google1");
                    lValuePairs.put("phoneKey", "1");
                    lValuePairs.put("orgName", "MobileImagingOrg");

                    String lSoapMsg = formatSOAPMessage("InsertPhoneTransaction", lValuePairs);

                    DefaultHttpClient mHttpClient = new DefaultHttpClient();
                    //                        mHttpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.R)
                    HttpPost mHttpPost = new HttpPost();

                    mHttpPost.setHeader("User-Agent", "UCSD Team");
                    mHttpPost.setHeader("Content-typURIe", "text/xml;charset=UTF-8");
                    //mHttpPost.setURI(URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx?op=InsertPhoneTransaction"));
                    mHttpPost.setURI(
                            URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx"));

                    StringEntity se = new StringEntity(lSoapMsg, HTTP.UTF_8);
                    se.setContentType("text/xml; charset=UTF-8");
                    mHttpPost.setEntity(se);
                    HttpResponse mResponse = mHttpClient.execute(mHttpPost, new BasicHttpContext());

                    String responseString = new BasicResponseHandler().handleResponse(mResponse);
                    parseXML(responseString);

                    //Todo: this is test code. Need to be implemented
                    //result = parseXML(testStr);
                    Log.i("test", "test:" + " " + responseString);
                    Log.i("test", "test: " + " " + map.size());

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // this part will be relocated in order to let the the server process picture
        if (map.size() == 0) {
            Intent display = new Intent(getApplicationContext(), DisplayInfoFailed.class);
            display.putExtra("result", (java.io.Serializable) iQAMsg);
            startActivity(display);
        } else {
            Intent display = new Intent(getApplicationContext(), DisplayInfo.class);
            display.putExtra("result", (java.io.Serializable) map);
            startActivity(display);

        }
    } else {
        // The file does not exist yet. Before starting the file observer, you
        // can update your UI to let the user know that the application is
        // waiting for the picture (for example, by displaying the thumbnail
        // image and a progress indicator).

        final File parentDirectory = pictureFile.getParentFile();
        FileObserver observer = new FileObserver(parentDirectory.getPath(),
                FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) {
            // Protect against additional pending events after CLOSE_WRITE
            // or MOVED_TO is handled.
            private boolean isFileWritten;

            @Override
            public void onEvent(int event, final String path) {
                if (!isFileWritten) {
                    // For safety, make sure that the file that was created in
                    // the directory is actually the one that we're expecting.
                    File affectedFile = new File(parentDirectory, path);
                    isFileWritten = affectedFile.equals(pictureFile);

                    if (isFileWritten) {
                        stopWatching();
                        // Now that the file is ready, recursively call
                        // processPictureWhenReady again (on the UI thread).
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new LongOperation().execute(picturePath);
                            }
                        });
                    }
                }
            }
        };
        observer.startWatching();

    }

}

From source file:com.charbgr.BlurNavigationDrawer.v4.BlurActionBarDrawerToggle.java

private Bitmap scaleBitmap(Bitmap myBitmap) {

    int width = (int) (myBitmap.getWidth() / mDownScaleFactor);
    int height = (int) (myBitmap.getHeight() / mDownScaleFactor);

    return Bitmap.createScaledBitmap(myBitmap, width, height, false);
}

From source file:com.lt.adamlee.aagame.GameView.java

public GameView(Context context, AttributeSet attrs) {
    super(context, attrs);
    ctx = context;//from  w w w  .  java 2 s.c o m
    getHolder().addCallback(this);
    setFocusable(true);
    DisplayMetrics DisplayMetrics = new DisplayMetrics();
    DisplayMetrics = context.getResources().getDisplayMetrics();
    screenW = DisplayMetrics.widthPixels;
    screenH = DisplayMetrics.heightPixels;
    this.mainpageimage = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.mainpageimage);
    this.mainpageimage = Bitmap.createScaledBitmap(this.mainpageimage, screenW, screenH, true);
    this.play = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.play);
    this.play = Bitmap.createScaledBitmap(this.play, (int) F.wf(90.0f), (int) F.wf(90.0f), true);
    this.cartoonbomb = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.cartoonbomb);
    this.cartoonbomb = Bitmap.createScaledBitmap(this.cartoonbomb, (int) F.hf(20.0f), (int) F.hf(20.0f), true);
    this.leaderboard = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.leaderboard);
    this.leaderboard = Bitmap.createScaledBitmap(this.leaderboard, (int) F.wf(70.0f), (int) F.wf(70.0f), true);
    this.moreapps = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.moreapps);
    this.moreapps = Bitmap.createScaledBitmap(this.moreapps, (int) F.wf(70.0f), (int) F.wf(70.0f), true);
    this.help = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.help);
    this.help = Bitmap.createScaledBitmap(this.help, (int) F.wf(70.0f), (int) F.wf(70.0f), true);
    this.about = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.about);
    this.about = Bitmap.createScaledBitmap(this.about, (int) F.wf(70.0f), (int) F.wf(70.0f), true);
    this.localAd = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.addimagebottom);
    view = new Circle();
    paint2 = new Paint();
    paint3 = new Paint();
    paint4 = new Paint();
    paint5 = new Paint();
    paint6 = new Paint();
    paint7 = new Paint();
    paint13 = new Paint();
    this.paint10 = new Paint();
    this.level = new LevelPage();
    circledrawboolean = new boolean[100];
    this.innercircletext = new Paint();
    this.innercircletext.setColor(-1);
    this.textsizetext = 10.0f;
    this.innercircletext.setTextSize(F.hf(this.textsizetext));
    this.innercircletext.setTypeface(tf);
    this.innercircletext.setTextAlign(Paint.Align.CENTER);
    this.innercircletext.setAntiAlias(true);
    this.innercircletext.setFilterBitmap(true);
    this.p9 = new Paint();
    this.paint20 = new Paint();
    this.paint21 = new Paint();
    this.pp = new Paint();
    this.eg = new ExitGame();
    paint4.setColor(ViewCompat.MEASURED_STATE_MASK);
    paint4.setAntiAlias(true);
    paint4.setFilterBitmap(true);
    paint4.setPathEffect(new DashPathEffect(new float[] { 30.0f, 0.0f }, 0.0f));
    paint4.setStrokeWidth(2.0f);
    paint4.setColor(ViewCompat.MEASURED_STATE_MASK);
    paint3.setColor(ViewCompat.MEASURED_STATE_MASK);
    paint3.setAntiAlias(true);
    paint3.setFilterBitmap(true);
    counter = 0;
    linecounter = -1;
    blinedraw = new boolean[100];
    blinedraw1 = new boolean[100];
    circleanimation = new boolean[100];
    savex = new int[100];
    savey = new int[100];
    rotation = new float[100];
    textsize = 20;
    a2 = 1200;
    tf = Typeface.createFromAsset(ctx.getAssets(), "Russo_One.ttf");
    textsize4 = 20;
    this.paint21.setTextSize(F.hf((float) textsize4));
    paint2.setTextSize(F.hf((float) textsize));
    textsize = 25;
    tf = Typeface.createFromAsset(ctx.getAssets(), "Russo_One.ttf");
    paint6.setTextSize(F.hf((float) textsize));
    this.textsize3 = 22;
    tf = Typeface.createFromAsset(ctx.getAssets(), "Russo_One.ttf");
    this.pp.setTextSize(F.hf((float) this.textsize3));
    a1 = MotionEventCompat.ACTION_MASK;
    changeangle = 2.0d;
    this.directioncounter = 1;
    NoOfInitialLines = 6;
    holdcounter = 0;
    hcm = 0;
    this.anim = new Levelfailedanimation();
    levelcounter = 1;
    textdisplayboolean = true;
    if (levelcounter > 0 && levelcounter < 4) {
        NoOfInitialLines = 6;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 3 && levelcounter < 7) {
        NoOfInitialLines = 8;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 6 && levelcounter < 10) {
        NoOfInitialLines = 2;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 9 && levelcounter < 13) {
        NoOfInitialLines = 4;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 12 && levelcounter < 16) {
        NoOfInitialLines = 6;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 15 && levelcounter < 19) {
        NoOfInitialLines = 3;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 18 && levelcounter < 22) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 21 && levelcounter < 25) {
        NoOfInitialLines = 8;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 24 && levelcounter < 28) {
        NoOfInitialLines = 4;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 27 && levelcounter < 31) {
        NoOfInitialLines = 2;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 30 && levelcounter < 34) {
        NoOfInitialLines = 1;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 33 && levelcounter < 37) {
        NoOfInitialLines = 8;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 36 && levelcounter < 40) {
        NoOfInitialLines = 2;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 39 && levelcounter < 43) {
        NoOfInitialLines = 4;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 42 && levelcounter < 46) {
        NoOfInitialLines = 6;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 45 && levelcounter < 49) {
        NoOfInitialLines = 3;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 48 && levelcounter < 52) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 51 && levelcounter < 55) {
        NoOfInitialLines = 7;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 54 && levelcounter < 58) {
        NoOfInitialLines = 8;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 57 && levelcounter < 61) {
        NoOfInitialLines = 2;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 606 && levelcounter < 64) {
        NoOfInitialLines = 4;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 63 && levelcounter < 67) {
        NoOfInitialLines = 3;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 66 && levelcounter < 70) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 69 && levelcounter < 73) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 72 && levelcounter < 76) {
        NoOfInitialLines = 9;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 75 && levelcounter < 79) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 78 && levelcounter < 82) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 81 && levelcounter < 85) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 84 && levelcounter < 88) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 87 && levelcounter < 91) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 90 && levelcounter < 94) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 93 && levelcounter < 97) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 96 && levelcounter < 101) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 100 && levelcounter < 105) {
        NoOfInitialLines = 8;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 104 && levelcounter < 108) {
        NoOfInitialLines = 3;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 107 && levelcounter < 111) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 110 && levelcounter < 114) {
        NoOfInitialLines = 4;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 113 && levelcounter < 117) {
        NoOfInitialLines = 3;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 116 && levelcounter < 121) {
        NoOfInitialLines = 4;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 120 && levelcounter < 124) {
        NoOfInitialLines = 8;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 123 && levelcounter < TransportMediator.KEYCODE_MEDIA_PAUSE) {
        NoOfInitialLines = 2;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > TransportMediator.KEYCODE_MEDIA_PLAY && levelcounter < 131) {
        NoOfInitialLines = 4;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > TransportMediator.KEYCODE_MEDIA_RECORD && levelcounter < 134) {
        NoOfInitialLines = 6;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 133 && levelcounter < 137) {
        NoOfInitialLines = 3;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 136 && levelcounter < 140) {
        NoOfInitialLines = 8;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 139 && levelcounter < 144) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 143 && levelcounter < 146) {
        NoOfInitialLines = 4;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 146 && levelcounter < 151) {
        NoOfInitialLines = 2;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 150 && levelcounter < 155) {
        NoOfInitialLines = 8;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 154 && levelcounter < 158) {
        NoOfInitialLines = 3;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 157 && levelcounter < 161) {
        NoOfInitialLines = 6;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 160 && levelcounter < 164) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 163 && levelcounter < 167) {
        NoOfInitialLines = 2;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 166 && levelcounter < 171) {
        NoOfInitialLines = 8;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 170 && levelcounter < 174) {
        NoOfInitialLines = 3;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 173 && levelcounter < 177) {
        NoOfInitialLines = 5;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 176 && levelcounter < 180) {
        NoOfInitialLines = 4;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 179 && levelcounter < 184) {
        NoOfInitialLines = 2;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 183 && levelcounter < 187) {
        NoOfInitialLines = 6;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 186 && levelcounter < 191) {
        NoOfInitialLines = 8;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 190 && levelcounter < 194) {
        NoOfInitialLines = 3;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 193 && levelcounter < 197) {
        NoOfInitialLines = 6;
        saveline = NoOfInitialLines;
    }
    if (levelcounter > 196 && levelcounter < 202) {
        NoOfInitialLines = 8;
        saveline = NoOfInitialLines;
    }
}

From source file:com.github.piasy.rxqrcode.RxQrCode.java

public static Observable<File> generateQrCodeFile(Context context, String content, int width, int height) {
    return Observable.fromEmitter(emitter -> {
        MultiFormatWriter writer = new MultiFormatWriter();
        Bitmap origin = null;/*  w w w .  j  a v  a 2 s.c  o  m*/
        Bitmap scaled = null;
        try {
            BitMatrix bm = writer.encode(content, BarcodeFormat.QR_CODE, QR_CODE_LENGTH, QR_CODE_LENGTH,
                    Collections.singletonMap(EncodeHintType.MARGIN, 0));
            origin = Bitmap.createBitmap(QR_CODE_LENGTH, QR_CODE_LENGTH, Bitmap.Config.ARGB_8888);

            for (int i = 0; i < QR_CODE_LENGTH; i++) {
                for (int j = 0; j < QR_CODE_LENGTH; j++) {
                    origin.setPixel(i, j, bm.get(i, j) ? Color.BLACK : Color.WHITE);
                }
            }
            scaled = Bitmap.createScaledBitmap(origin, width, height, true);
            File dir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            if (dir == null) {
                emitter.onError(new IllegalStateException("external file system unavailable!"));
                return;
            }
            String fileName = "rx_qr_" + System.currentTimeMillis() + ".png";
            File localFile = new File(dir, fileName);

            FileOutputStream outputStream = new FileOutputStream(localFile);
            scaled.compress(Bitmap.CompressFormat.PNG, 85, outputStream);
            outputStream.flush();
            outputStream.close();

            emitter.onNext(localFile);
            emitter.onCompleted();
        } catch (WriterException | IOException e) {
            emitter.onError(e);
        } finally {
            if (origin != null) {
                origin.recycle();
            }
            if (scaled != null) {
                scaled.recycle();
            }
        }
    }, Emitter.BackpressureMode.BUFFER);
}

From source file:com.alucas.snorlax.module.feature.encounter.EncounterNotification.java

@SuppressWarnings("deprecation")
void show(int pokemonNumber, String pokemonName, Gender gender, double iv, int attack, int defense, int stamina,
        int cp, double level, int hp, double baseWeight, double weight, double baseHeight, double height,
        MoveSettings fastMove, MoveSettings chargeMove, double fleeRate, double pokeRate, double greatRate,
        double ultraRate, PokemonType type1, PokemonType type2, PokemonRarity pokemonClass) {
    final double weightRatio = weight / baseWeight;
    final double heightRatio = height / baseHeight;
    final MODIFIER resourceModifier = (pokemonNumber == PokemonId.PIKACHU_VALUE ? MODIFIER.FAN
            : pokemonNumber == PokemonId.RATTATA_VALUE && heightRatio < 0.80 ? MODIFIER.YOUNGSTER
                    : pokemonNumber == PokemonId.MAGIKARP_VALUE && weightRatio > 1.30 ? MODIFIER.FISHERMAN
                            : MODIFIER.NO);

    final String genderSymbol = PokemonFormat.formatGender(mResources, gender);
    final String fastMoveName = PokemonFormat.formatMove(fastMove.getMovementId());
    final String chargeMoveName = PokemonFormat.formatMove(chargeMove.getMovementId());
    final String fastMoveTypeName = PokemonFormat.formatType(fastMove.getPokemonType());
    final String chargeMoveTypeName = PokemonFormat.formatType(chargeMove.getPokemonType());
    final String fastMoveTypeSymbol = TYPE_SYMBOL.containsKey(fastMove.getPokemonType())
            ? mResources.getString(TYPE_SYMBOL.get(fastMove.getPokemonType()))
            : "?";
    final String chargeMoveTypeSymbol = TYPE_SYMBOL.containsKey(chargeMove.getPokemonType())
            ? mResources.getString(TYPE_SYMBOL.get(chargeMove.getPokemonType()))
            : "?";

    final Map<String, Pair<String, Integer>> symbols = getSymbolReplacementTable();
    new Handler(Looper.getMainLooper()).post(() -> {
        Notification notification = new NotificationCompat.Builder(mContext)
                .setSmallIcon(R.drawable.ic_pokeball)
                .setLargeIcon(Bitmap.createScaledBitmap(
                        BitmapFactory.decodeResource(mResources,
                                Resource.getPokemonResourceId(mContext, mResources, pokemonNumber,
                                        resourceModifier)),
                        Resource.getLargeIconWidth(mResources), Resource.getLargeIconHeight(mResources), false))
                .setContentTitle(EncounterFormat.format(
                        mContext.getString(R.string.notification_title, genderSymbol, pokemonName, cp, level),
                        symbols))/* w ww . j  a  v a 2s .com*/
                .setContentText(EncounterFormat.format(mContext.getString(R.string.notification_content, iv,
                        fleeRate, pokeRate, greatRate, ultraRate), symbols))
                .setStyle(new NotificationCompat.InboxStyle()
                        .addLine(EncounterFormat
                                .format(mContext.getString(R.string.notification_category_stats_content_iv, iv,
                                        attack, defense, stamina), symbols))
                        .addLine(EncounterFormat.format(mContext.getString(
                                R.string.notification_category_stats_content_hp, hp, fleeRate), symbols))
                        .addLine(EncounterFormat
                                .bold(mContext.getString(R.string.notification_category_moves_title)))
                        .addLine(EncounterFormat
                                .format(mContext.getString(R.string.notification_category_moves_fast,
                                        fastMoveName, fastMoveTypeName, fastMove.getPower()), symbols))
                        .addLine(
                                EncounterFormat.format(
                                        mContext.getString(R.string.notification_category_moves_charge,
                                                chargeMoveName, chargeMoveTypeName, chargeMove.getPower()),
                                        symbols))
                        .addLine(EncounterFormat
                                .bold(mContext.getString(R.string.notification_categoty_catch_title)))
                        .addLine(EncounterFormat
                                .format(mContext.getString(R.string.notification_categoty_catch_content,
                                        pokeRate, greatRate, ultraRate), symbols))
                        .setSummaryText(getFooter(type1, type2, pokemonClass)))
                .setColor(ContextCompat.getColor(mContext, R.color.red_700)).setAutoCancel(true)
                .setVibrate(new long[] { 0 }).setPriority(Notification.PRIORITY_MAX)
                .setCategory(NotificationCompat.CATEGORY_ALARM).build();

        hideIcon(notification);

        mNotificationManager.notify(NotificationId.ID_ENCOUNTER, notification);
    });
}

From source file:com.anyline.reactnative.DocumentActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(getResources().getIdentifier("activity_scan_document", "layout", getPackageName()));
    //Set the flag to keep the screen on (otherwise the screen may go dark during scanning)
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    imageViewResult = (ImageView) findViewById(
            getResources().getIdentifier("image_result", "id", getPackageName()));
    errorMessageLayout = (FrameLayout) findViewById(
            getResources().getIdentifier("error_message_layout", "id", getPackageName()));
    errorMessage = (TextView) findViewById(
            getResources().getIdentifier("error_message", "id", getPackageName()));

    documentScanView = (DocumentScanView) findViewById(
            getResources().getIdentifier("document_scan_view", "id", getPackageName()));
    // add a camera open listener that will be called when the camera is opened or an error occurred
    //  this is optional (if not set a RuntimeException will be thrown if an error occurs)
    documentScanView.setCameraOpenListener(this);
    // the view can be configured via a json file in the assets, and this config is set here
    // (alternatively it can be configured via xml, see the Energy Example for that)
    JSONObject jsonObject;//w w  w.  j av  a2 s.  co  m
    try {
        jsonObject = new JSONObject(configJson);
    } catch (Exception e) {
        //JSONException or IllegalArgumentException is possible, return it to javascript
        finishWithError("error_invalid_json_data");
        return;
    }

    documentScanView.setConfig(new AnylineViewConfig(this, jsonObject));

    // Optional: Set a ratio you want the documents to be restricted to. default is set to DIN_AX
    documentScanView.setDocumentRatios(DocumentScanView.DocumentRatio.DIN_AX_PORTRAIT.getRatio());

    // Optional: Set a maximum deviation for the ratio. 0.15 is the default
    documentScanView.setMaxDocumentRatioDeviation(0.15);

    // initialize Anyline with the license key and a Listener that is called if a result is found
    documentScanView.initAnyline(licenseKey, new DocumentResultListener() {
        @Override
        public void onResult(DocumentResult documentResult) {

            // handle the result document images here
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            AnylineImage transformedImage = documentResult.getResult();
            AnylineImage fullFrame = documentResult.getFullImage();

            imageViewResult
                    .setImageBitmap(Bitmap.createScaledBitmap(transformedImage.getBitmap(), 100, 160, false));

            /**
             * IMPORTANT: cache provided frames here, and release them at the end of this onResult. Because
             * keeping them in memory (e.g. setting the full frame to an ImageView)
             * will result in a OutOfMemoryError soon. This error is reported in {@link #onTakePictureError
             * (Throwable)}
             *
             * Use a DiskCache http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#disk-cache
             * for example
             *
             */
            File outDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "ok");
            outDir.mkdir();
            // change the file ending to png if you want a png
            File outFile = new File(outDir, "" + System.currentTimeMillis() + ".jpg");
            try {
                // convert the transformed image into a gray scaled image internally
                // transformedImage.getGrayCvMat(false);
                // get the transformed image as bitmap
                // Bitmap bmp = transformedImage.getBitmap();
                // save the image with quality 100 (only used for jpeg, ignored for png)
                transformedImage.save(outFile, 100);
                showToast(getString(
                        getResources().getIdentifier("document_image_saved_to", "string", getPackageName()))
                        + " " + outFile.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }

            // release the images
            transformedImage.release();
            fullFrame.release();

            JSONObject jsonResult = new JSONObject();
            try {
                jsonResult.put("imagePath", outFile.getAbsolutePath());
                jsonResult.put("outline", jsonForOutline(documentResult.getOutline()));
                jsonResult.put("confidence", documentResult.getConfidence());

            } catch (Exception jsonException) {
                //should not be possible
                Log.e(TAG, "Error while putting image path to json.", jsonException);
            }

            Boolean cancelOnResult = true;

            JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(configJson);
                cancelOnResult = jsonObject.getBoolean("cancelOnResult");
            } catch (Exception e) {

            }

            if (cancelOnResult) {
                ResultReporter.onResult(jsonResult, true);
                setResult(AnylineSDKPlugin.RESULT_OK);
                finish();
            } else {
                ResultReporter.onResult(jsonResult, false);
            }

        }

        @Override
        public void onPreviewProcessingSuccess(AnylineImage anylineImage) {
            // this is called after the preview of the document is completed, and a full picture will be
            // processed automatically
        }

        @Override
        public void onPreviewProcessingFailure(DocumentScanView.DocumentError documentError) {
            // this is called on any error while processing the document image
            // Note: this is called every time an error occurs in a run, so that might be quite often
            // An error message should only be presented to the user after some time

            showErrorMessageFor(documentError);
        }

        @Override
        public void onPictureProcessingFailure(DocumentScanView.DocumentError documentError) {

            showErrorMessageFor(documentError, true);
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            // if there is a problem, here is how images could be saved in the error case
            // this will be a full, not cropped, not transformed image
            AnylineImage image = documentScanView.getCurrentFullImage();

            if (image != null) {
                File outDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "error");
                outDir.mkdir();
                File outFile = new File(outDir,
                        "" + System.currentTimeMillis() + documentError.name() + ".jpg");
                try {
                    image.save(outFile, 100);
                    Log.d(TAG, "error image saved to " + outFile.getAbsolutePath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image.release();
            }
        }

        @Override
        public boolean onDocumentOutlineDetected(List<PointF> list, boolean documentShapeAndBrightnessValid) {
            // is called when the outline of the document is detected. return true if the outline is consumed by
            // the implementation here, false if the outline should be drawn by the DocumentScanView
            lastOutline = list; // saving the outline for the animations
            return false;
        }

        @Override
        public void onTakePictureSuccess() {
            // this is called after the image has been captured from the camera and is about to be processed
            progressDialog = ProgressDialog.show(DocumentActivity.this,
                    getString(getResources().getIdentifier("document_processing_picture_header", "string",
                            getPackageName())),
                    getString(getResources().getIdentifier("document_processing_picture", "string",
                            getPackageName())),
                    true);

            if (errorMessageAnimator != null && errorMessageAnimator.isRunning()) {

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        errorMessageAnimator.cancel();
                        errorMessageLayout.setVisibility(View.GONE);
                    }
                });

            }
        }

        @Override
        public void onTakePictureError(Throwable throwable) {
            // This is called if the image could not be captured from the camera (most probably because of an
            // OutOfMemoryError)
            throw new RuntimeException(throwable);
        }

    });

    // optionally stop the scan once a valid result was returned
    //        documentScanView.setCancelOnResult(cancelOnResult);

}

From source file:io.anyline.cordova.DocumentActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(getResources().getIdentifier("activity_scan_document", "layout", getPackageName()));
    //Set the flag to keep the screen on (otherwise the screen may go dark during scanning)
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    imageViewResult = (ImageView) findViewById(
            getResources().getIdentifier("image_result", "id", getPackageName()));
    errorMessageLayout = (FrameLayout) findViewById(
            getResources().getIdentifier("error_message_layout", "id", getPackageName()));
    errorMessage = (TextView) findViewById(
            getResources().getIdentifier("error_message", "id", getPackageName()));

    documentScanView = (DocumentScanView) findViewById(
            getResources().getIdentifier("document_scan_view", "id", getPackageName()));
    // add a camera open listener that will be called when the camera is opened or an error occurred
    //  this is optional (if not set a RuntimeException will be thrown if an error occurs)
    documentScanView.setCameraOpenListener(this);
    // the view can be configured via a json file in the assets, and this config is set here
    // (alternatively it can be configured via xml, see the Energy Example for that)
    JSONObject jsonObject;//from w w w  . jav  a2  s .  co m
    try {
        jsonObject = new JSONObject(configJson);
    } catch (Exception e) {
        //JSONException or IllegalArgumentException is possible, return it to javascript
        finishWithError(Resources.getString(this, "error_invalid_json_data") + "\n" + e.getLocalizedMessage());
        return;
    }

    documentScanView.setConfig(new AnylineViewConfig(this, jsonObject));

    // Optional: Set a ratio you want the documents to be restricted to. default is set to DIN_AX
    documentScanView.setDocumentRatios(DocumentScanView.DocumentRatio.DIN_AX_PORTRAIT.getRatio());

    // Optional: Set a maximum deviation for the ratio. 0.15 is the default
    documentScanView.setMaxDocumentRatioDeviation(0.15);

    // initialize Anyline with the license key and a Listener that is called if a result is found
    documentScanView.initAnyline(licenseKey, new DocumentResultListener() {
        @Override
        public void onResult(AnylineImage transformedImage, AnylineImage fullFrame,
                List<PointF> documentOutline) {

            // handle the result document images here
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            imageViewResult
                    .setImageBitmap(Bitmap.createScaledBitmap(transformedImage.getBitmap(), 100, 160, false));

            /**
             * IMPORTANT: cache provided frames here, and release them at the end of this onResult. Because
             * keeping them in memory (e.g. setting the full frame to an ImageView)
             * will result in a OutOfMemoryError soon. This error is reported in {@link #onTakePictureError
             * (Throwable)}
             *
             * Use a DiskCache http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#disk-cache
             * for example
             *
             */
            File outDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "ok");
            outDir.mkdir();
            // change the file ending to png if you want a png
            File outFile = new File(outDir, "" + System.currentTimeMillis() + ".jpg");
            try {
                // convert the transformed image into a gray scaled image internally
                // transformedImage.getGrayCvMat(false);
                // get the transformed image as bitmap
                // Bitmap bmp = transformedImage.getBitmap();
                // save the image with quality 100 (only used for jpeg, ignored for png)
                transformedImage.save(outFile, 100);
                showToast(getString(
                        getResources().getIdentifier("document_image_saved_to", "string", getPackageName()))
                        + " " + outFile.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }

            // release the images
            transformedImage.release();
            fullFrame.release();

            JSONObject jsonResult = new JSONObject();
            try {
                jsonResult.put("imagePath", outFile.getAbsolutePath());
            } catch (Exception jsonException) {
                //should not be possible
                Log.e(TAG, "Error while putting image path to json.", jsonException);
            }

            Boolean cancelOnResult = true;

            JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(configJson);
                cancelOnResult = jsonObject.getBoolean("cancelOnResult");
            } catch (Exception e) {

            }

            if (cancelOnResult) {
                ResultReporter.onResult(jsonResult, true);
                setResult(AnylinePlugin.RESULT_OK);
                finish();
            } else {
                ResultReporter.onResult(jsonResult, false);
            }

        }

        @Override
        public void onPreviewProcessingSuccess(AnylineImage anylineImage) {
            // this is called after the preview of the document is completed, and a full picture will be
            // processed automatically
        }

        @Override
        public void onPreviewProcessingFailure(DocumentScanView.DocumentError documentError) {
            // this is called on any error while processing the document image
            // Note: this is called every time an error occurs in a run, so that might be quite often
            // An error message should only be presented to the user after some time

            showErrorMessageFor(documentError);
        }

        @Override
        public void onPictureProcessingFailure(DocumentScanView.DocumentError documentError) {

            showErrorMessageFor(documentError, true);
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            // if there is a problem, here is how images could be saved in the error case
            // this will be a full, not cropped, not transformed image
            AnylineImage image = documentScanView.getCurrentFullImage();

            if (image != null) {
                File outDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "error");
                outDir.mkdir();
                File outFile = new File(outDir,
                        "" + System.currentTimeMillis() + documentError.name() + ".jpg");
                try {
                    image.save(outFile, 100);
                    Log.d(TAG, "error image saved to " + outFile.getAbsolutePath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image.release();
            }
        }

        @Override
        public boolean onDocumentOutlineDetected(List<PointF> list, boolean documentShapeAndBrightnessValid) {
            // is called when the outline of the document is detected. return true if the outline is consumed by
            // the implementation here, false if the outline should be drawn by the DocumentScanView
            lastOutline = list; // saving the outline for the animations
            return false;
        }

        @Override
        public void onTakePictureSuccess() {
            // this is called after the image has been captured from the camera and is about to be processed
            progressDialog = ProgressDialog.show(DocumentActivity.this,
                    getString(getResources().getIdentifier("document_processing_picture_header", "string",
                            getPackageName())),
                    getString(getResources().getIdentifier("document_processing_picture", "string",
                            getPackageName())),
                    true);

            if (errorMessageAnimator != null && errorMessageAnimator.isRunning()) {

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        errorMessageAnimator.cancel();
                        errorMessageLayout.setVisibility(View.GONE);
                    }
                });

            }
        }

        @Override
        public void onTakePictureError(Throwable throwable) {
            // This is called if the image could not be captured from the camera (most probably because of an
            // OutOfMemoryError)
            throw new RuntimeException(throwable);
        }

    });

    // optionally stop the scan once a valid result was returned
    //        documentScanView.setCancelOnResult(cancelOnResult);

}