Example usage for android.graphics Bitmap copy

List of usage examples for android.graphics Bitmap copy

Introduction

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

Prototype

public Bitmap copy(Config config, boolean isMutable) 

Source Link

Document

Tries to make a new bitmap based on the dimensions of this bitmap, setting the new bitmap's config to the one specified, and then copying this bitmap's pixels into the new bitmap.

Usage

From source file:edu.mum.ml.group7.guessasketch.android.EasyPaint.java

/**
 * This takes the screenshot of the whole screen. Is this a good thing?
 *//*from w  ww.  j  a  v  a2 s  .  c o m*/
private File sendScreenshot(boolean showToast, ApiCallType callType, String label) {
    saveButton.setVisibility(View.INVISIBLE);
    loader.setVisibility(View.VISIBLE);

    View v = findViewById(R.id.CanvasId);
    v.setDrawingCacheEnabled(true);
    Bitmap cachedBitmap = v.getDrawingCache();
    Bitmap copyBitmap = toGrayscale(cachedBitmap.copy(Bitmap.Config.RGB_565, true));
    v.destroyDrawingCache();
    FileOutputStream output = null;
    File file = null;
    try {
        File path = Places.getScreenshotFolder();
        Calendar cal = Calendar.getInstance();

        file = new File(path,

                cal.get(Calendar.YEAR) + "_" + (1 + cal.get(Calendar.MONTH)) + "_"
                        + cal.get(Calendar.DAY_OF_MONTH) + "_" + cal.get(Calendar.HOUR_OF_DAY) + "_"
                        + cal.get(Calendar.MINUTE) + "_" + cal.get(Calendar.SECOND) + ".jpg");
        output = new FileOutputStream(file);
        copyBitmap.compress(CompressFormat.JPEG, 60, output);
        sendPost(file, callType, label);

    } catch (FileNotFoundException e) {
        file = null;
        e.printStackTrace();
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    if (file != null) {
        if (showToast)
            Toast.makeText(getApplicationContext(), String
                    .format(getResources().getString(R.string.saved_your_location_to), file.getAbsolutePath()),
                    Toast.LENGTH_LONG).show();
        /*
        // sending a broadcast to the media scanner so it will scan the new
        // screenshot.
        Intent requestScan = new Intent(
            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        requestScan.setData(Uri.fromFile(file));
        sendBroadcast(requestScan); */

        return file;
    } else {
        return null;
    }
}

From source file:Main.java

public static Bitmap doBlur(Bitmap sentBitmap, int radius, boolean canReuseInBitmap) {

    // Stack Blur v1.0 from
    // http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
    ////from w  w w  . ja  v a 2  s .com
    // Java Author: Mario Klingemann <mario at quasimondo.com>
    // http://incubator.quasimondo.com
    // created Feburary 29, 2004
    // Android port : Yahel Bouaziz <yahel at kayenko.com>
    // http://www.kayenko.com
    // ported april 5th, 2012

    // This is a compromise between Gaussian Blur and Box blur
    // It creates much better looking blurs than Box Blur, but is
    // 7x faster than my Gaussian Blur implementation.
    //
    // I called it Stack Blur because this describes best how this
    // filter works internally: it creates a kind of moving stack
    // of colors whilst scanning through the image. Thereby it
    // just has to add one new block of color to the right side
    // of the stack and remove the leftmost color. The remaining
    // colors on the topmost layer of the stack are either added on
    // or reduced by one, depending on if they are on the right or
    // on the left side of the stack.
    //
    // If you are using this algorithm in your code please add
    // the following line:
    //
    // Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>

    Bitmap bitmap;
    if (canReuseInBitmap) {
        bitmap = sentBitmap;
    } else {
        Bitmap.Config config = sentBitmap.getConfig();
        config = config != null ? config : Bitmap.Config.RGB_565;
        bitmap = sentBitmap.copy(config, true);
    }

    if (radius < 1) {
        return (null);
    }

    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int[] pix = new int[w * h];
    bitmap.getPixels(pix, 0, w, 0, 0, w, h);

    int wm = w - 1;
    int hm = h - 1;
    int wh = w * h;
    int div = radius + radius + 1;

    int r[] = new int[wh];
    int g[] = new int[wh];
    int b[] = new int[wh];
    int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
    int vmin[] = new int[Math.max(w, h)];

    int divsum = (div + 1) >> 1;
    divsum *= divsum;
    int dv[] = new int[256 * divsum];
    for (i = 0; i < 256 * divsum; i++) {
        dv[i] = (i / divsum);
    }

    yw = yi = 0;

    int[][] stack = new int[div][3];
    int stackpointer;
    int stackstart;
    int[] sir;
    int rbs;
    int r1 = radius + 1;
    int routsum, goutsum, boutsum;
    int rinsum, ginsum, binsum;

    for (y = 0; y < h; y++) {
        rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
        for (i = -radius; i <= radius; i++) {
            p = pix[yi + Math.min(wm, Math.max(i, 0))];
            sir = stack[i + radius];
            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);
            rbs = r1 - Math.abs(i);
            rsum += sir[0] * rbs;
            gsum += sir[1] * rbs;
            bsum += sir[2] * rbs;
            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
            }
        }
        stackpointer = radius;

        for (x = 0; x < w; x++) {

            r[yi] = dv[rsum];
            g[yi] = dv[gsum];
            b[yi] = dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];

            if (y == 0) {
                vmin[x] = Math.min(x + radius + 1, wm);
            }
            p = pix[yw + vmin[x]];

            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[(stackpointer) % div];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];

            yi++;
        }
        yw += w;
    }
    for (x = 0; x < w; x++) {
        rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
        yp = -radius * w;
        for (i = -radius; i <= radius; i++) {
            yi = Math.max(0, yp) + x;

            sir = stack[i + radius];

            sir[0] = r[yi];
            sir[1] = g[yi];
            sir[2] = b[yi];

            rbs = r1 - Math.abs(i);

            rsum += r[yi] * rbs;
            gsum += g[yi] * rbs;
            bsum += b[yi] * rbs;

            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
            }

            if (i < hm) {
                yp += w;
            }
        }
        yi = x;
        stackpointer = radius;
        for (y = 0; y < h; y++) {
            // Preserve alpha channel: ( 0xff000000 & pix[yi] )
            pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];

            if (x == 0) {
                vmin[y] = Math.min(y + r1, hm) * w;
            }
            p = x + vmin[y];

            sir[0] = r[p];
            sir[1] = g[p];
            sir[2] = b[p];

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[stackpointer];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];

            yi += w;
        }
    }

    bitmap.setPixels(pix, 0, w, 0, 0, w, h);

    return bitmap;
}

From source file:Main.java

@NonNull
public static Bitmap doBlur(@NonNull Bitmap sentBitmap, int radius, boolean canReuseInBitmap) {

    // Stack Blur v1.0 from
    // http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
    //// w  w w .  ja  v a2s  . c o m
    // Java Author: Mario Klingemann <mario at quasimondo.com>
    // http://incubator.quasimondo.com
    // created Feburary 29, 2004
    // Android port : Yahel Bouaziz <yahel at kayenko.com>
    // http://www.kayenko.com
    // ported april 5th, 2012

    // Modified by Artem Chepurnoy <ynkr.wang@gmail.com> for EasyNotification

    // This is a compromise between Gaussian Blur and Box blur
    // It creates much better looking blurs than Box Blur, but is
    // 7x faster than my Gaussian Blur implementation.
    //
    // I called it Stack Blur because this describes best how this
    // filter works internally: it creates a kind of moving stack
    // of colors whilst scanning through the image. Thereby it
    // just has to add one new block of color to the right side
    // of the stack and remove the leftmost color. The remaining
    // colors on the topmost layer of the stack are either added on
    // or reduced by one, depending on if they are on the right or
    // on the left side of the stack.
    //
    // If you are using this algorithm in your code please add
    // the following line:
    //
    // Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>

    Bitmap bitmap;
    if (canReuseInBitmap) {
        bitmap = sentBitmap;
    } else {
        Bitmap.Config config = sentBitmap.getConfig();
        config = config != null ? config : Bitmap.Config.RGB_565;
        bitmap = sentBitmap.copy(config, true);
    }

    if (radius < 1) {
        return (null);
    }

    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int[] pix = new int[w * h];
    bitmap.getPixels(pix, 0, w, 0, 0, w, h);

    int wm = w - 1;
    int hm = h - 1;
    int wh = w * h;
    int div = radius + radius + 1;

    int r[] = new int[wh];
    int g[] = new int[wh];
    int b[] = new int[wh];
    int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
    int vmin[] = new int[Math.max(w, h)];

    int divsum = (div + 1) >> 1;
    divsum *= divsum;
    int dv[] = new int[256 * divsum];
    for (i = 0; i < 256 * divsum; i++) {
        dv[i] = (i / divsum);
    }

    yw = yi = 0;

    int[][] stack = new int[div][3];
    int stackpointer;
    int stackstart;
    int[] sir;
    int rbs;
    int r1 = radius + 1;
    int routsum, goutsum, boutsum;
    int rinsum, ginsum, binsum;

    for (y = 0; y < h; y++) {
        rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
        for (i = -radius; i <= radius; i++) {
            p = pix[yi + Math.min(wm, Math.max(i, 0))];
            sir = stack[i + radius];
            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);
            rbs = r1 - Math.abs(i);
            rsum += sir[0] * rbs;
            gsum += sir[1] * rbs;
            bsum += sir[2] * rbs;
            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
            }
        }
        stackpointer = radius;

        for (x = 0; x < w; x++) {

            r[yi] = dv[rsum];
            g[yi] = dv[gsum];
            b[yi] = dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];

            if (y == 0) {
                vmin[x] = Math.min(x + radius + 1, wm);
            }
            p = pix[yw + vmin[x]];

            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[(stackpointer) % div];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];

            yi++;
        }
        yw += w;
    }
    for (x = 0; x < w; x++) {
        rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
        yp = -radius * w;
        for (i = -radius; i <= radius; i++) {
            yi = Math.max(0, yp) + x;

            sir = stack[i + radius];

            sir[0] = r[yi];
            sir[1] = g[yi];
            sir[2] = b[yi];

            rbs = r1 - Math.abs(i);

            rsum += r[yi] * rbs;
            gsum += g[yi] * rbs;
            bsum += b[yi] * rbs;

            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
            }

            if (i < hm) {
                yp += w;
            }
        }
        yi = x;
        stackpointer = radius;
        for (y = 0; y < h; y++) {
            // Preserve alpha channel: ( 0xff000000 & pix[yi] )
            pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];

            if (x == 0) {
                vmin[y] = Math.min(y + r1, hm) * w;
            }
            p = x + vmin[y];

            sir[0] = r[p];
            sir[1] = g[p];
            sir[2] = b[p];

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[stackpointer];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];

            yi += w;
        }
    }

    bitmap.setPixels(pix, 0, w, 0, 0, w, h);

    return bitmap;
}

From source file:com.waz.zclient.pages.main.drawing.DrawingFragment.java

private void drawSketchEditText() {
    if (sketchEditTextView.getVisibility() == View.VISIBLE) {
        sketchEditTextView.setAlpha(TEXT_ALPHA_VISIBLE);
        sketchEditTextView.setCursorVisible(false);
        //This has to be on a post otherwise the setAlpha and setCursor won't be noticeable in the drawing cache
        getView().post(new Runnable() {
            @Override/*from w w w .  j av a  2 s .  c  o  m*/
            public void run() {
                sketchEditTextView.setDrawingCacheEnabled(true);
                Bitmap bitmapDrawingCache = sketchEditTextView.getDrawingCache();
                if (bitmapDrawingCache != null) {
                    FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) sketchEditTextView
                            .getLayoutParams();
                    drawingCanvasView.showText();
                    drawingCanvasView.drawTextBitmap(
                            bitmapDrawingCache.copy(bitmapDrawingCache.getConfig(), true), params.leftMargin,
                            params.topMargin, sketchEditTextView.getText().toString(),
                            sketchEditTextView.getSketchScale());
                } else {
                    drawingCanvasView.drawTextBitmap(null, 0, 0, "", 1.0f);
                }
                sketchEditTextView.setDrawingCacheEnabled(false);
                sketchEditTextView.setAlpha(TEXT_ALPHA_INVISIBLE);
            }
        });
    }
}

From source file:br.com.viniciuscr.notification2android.mediaPlayer.MusicUtils.java

/**
 * Get album art for specified album. You should not pass in the album id
 * for the "unknown" album here (use -1 instead)
 *///from w  ww.  j av a  2s .  com
public static Bitmap getArtwork(Context context, long song_id, long album_id, boolean allowdefault) {

    if (album_id < 0) {
        // This is something that is not in the database, so get the album art directly
        // from the file.
        if (song_id >= 0) {
            Bitmap bm = getArtworkFromFile(context, song_id, -1);
            if (bm != null) {
                return bm;
            }
        }
        if (allowdefault) {
            return getDefaultArtwork(context);
        }
        return null;
    }

    ContentResolver res = context.getContentResolver();
    Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
    if (uri != null) {
        InputStream in = null;
        try {
            in = res.openInputStream(uri);
            return BitmapFactory.decodeStream(in, null, sBitmapOptions);
        } catch (FileNotFoundException ex) {
            // The album art thumbnail does not actually exist. Maybe the user deleted it, or
            // maybe it never existed to begin with.
            Bitmap bm = getArtworkFromFile(context, song_id, album_id);
            if (bm != null) {
                if (bm.getConfig() == null) {
                    bm = bm.copy(Bitmap.Config.RGB_565, false);
                    if (bm == null && allowdefault) {
                        return getDefaultArtwork(context);
                    }
                }
            } else if (allowdefault) {
                bm = getDefaultArtwork(context);
            }
            return bm;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
            }
        }
    }

    return null;
}

From source file:com.example.angel.parkpanda.MainActivity.java

public Bitmap drawTextToBitmap(int gResId, String gText) {
    Resources resources = getResources();
    float scale = resources.getDisplayMetrics().density;
    Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);
    android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();

    if (bitmapConfig == null) {
        bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
    }//from w ww. ja v a  2s .  c o  m
    bitmap = bitmap.copy(bitmapConfig, true);
    Canvas canvas = new Canvas(bitmap);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.rgb(0, 0, 0));
    paint.setTextSize((int) (15 * scale));
    paint.setShadowLayer(1f, 0f, 1f, Color.BLACK);

    Rect bounds = new Rect();
    paint.getTextBounds(gText, 0, gText.length(), bounds);
    int x = (bitmap.getWidth() - bounds.width()) / 2;
    int y = (bitmap.getHeight() + bounds.height()) / 2 - 10;
    canvas.drawText(gText, x, y, paint);

    return bitmap;
}

From source file:com.mjhram.geodata.GpsMainActivity.java

public Bitmap drawMultilineTextToBitmap(Context gContext, Bitmap bitmap, String gText) {
    // prepare canvas
    Resources resources = gContext.getResources();
    float scale = resources.getDisplayMetrics().density;
    //Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);

    android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
    // set default bitmap config if none
    if (bitmapConfig == null) {
        bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
    }/*from  w ww  . j av  a2 s .c  o m*/
    // resource bitmaps are imutable,
    // so we need to convert it to mutable one
    bitmap = bitmap.copy(bitmapConfig, true);

    Canvas canvas = new Canvas(bitmap);

    // new antialiased Paint
    TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    // text color - #3D3D3D
    paint.setColor(Color.rgb(61, 61, 61));
    // text size in pixels
    paint.setTextSize((int) (20 * scale));
    // text shadow
    paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
    //canvas.drawText("This is", 100, 100, paint);
    //canvas.drawText("multi-line", 100, 150, paint);
    //canvas.drawText("text", 100, 200, paint);

    // set text width to canvas width minus 16dp padding
    int textWidth = canvas.getWidth() - (int) (16 * scale);

    // init StaticLayout for text
    StaticLayout textLayout = new StaticLayout(gText, paint, textWidth, Layout.Alignment.ALIGN_CENTER, 1.0f,
            0.0f, false);

    // get height of multiline text
    int textHeight = textLayout.getHeight();

    // get position of text's top left corner
    float x = (bitmap.getWidth() - textWidth) / 2;
    float y = bitmap.getHeight() - textHeight;

    // draw text to the Canvas center
    canvas.save();
    canvas.translate(x, y);
    textLayout.draw(canvas);
    canvas.restore();

    return bitmap;
}

From source file:org.telegram.ui.ChannelCreateActivity.java

private ChipSpan createAndPutChipForUser(TLRPC.User user) {
    try {//w ww. j av a  2  s  .c om
        LayoutInflater lf = (LayoutInflater) ApplicationLoader.applicationContext
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View textView = lf.inflate(R.layout.group_create_bubble, null);
        TextView text = (TextView) textView.findViewById(R.id.bubble_text_view);
        String name = UserObject.getUserName(user);
        if (name.length() == 0 && user.phone != null && user.phone.length() != 0) {
            name = PhoneFormat.getInstance().format("+" + user.phone);
        }
        text.setText(name + ", ");

        int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        textView.measure(spec, spec);
        textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
        Bitmap b = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(b);
        canvas.translate(-textView.getScrollX(), -textView.getScrollY());
        textView.draw(canvas);
        textView.setDrawingCacheEnabled(true);
        Bitmap cacheBmp = textView.getDrawingCache();
        Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
        textView.destroyDrawingCache();

        final BitmapDrawable bmpDrawable = new BitmapDrawable(b);
        bmpDrawable.setBounds(0, 0, b.getWidth(), b.getHeight());

        SpannableStringBuilder ssb = new SpannableStringBuilder("");
        ChipSpan span = new ChipSpan(bmpDrawable, ImageSpan.ALIGN_BASELINE);
        allSpans.add(span);
        selectedContacts.put(user.id, span);
        for (ImageSpan sp : allSpans) {
            ssb.append("<<");
            ssb.setSpan(sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        nameTextView.setText(ssb);
        nameTextView.setSelection(ssb.length());
        return span;
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
    return null;
}

From source file:com.dastardlylabs.ti.ocrdroid.OcrdroidModule.java

@Kroll.method
@SuppressWarnings("rawtypes")
public String ocr(HashMap _config) {
    assert (_config != null);
    String dataParentPath = getTessDataDirectory().getAbsolutePath(), //= (String) _config.get("dataParent"),
            imagePath = StorageHelper.stripFileUri((String) _config.get("image")),
            language = (String) _config.get("lang");

    try {//from   ww  w.j a  v  a 2s . com
        if (!tessDataExists())
            unpackTessData();
    } catch (Exception e) {
        // catch failure and bubble up failure message and options
        // else continue.
    }

    Log.d(LCAT, "ocr called");
    Log.d(LCAT, "Setting parent directory for tessdata as DATAPATH".replace("DATAPATH",
            dataParentPath /*DATA_PATH*/));

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 2;
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

    Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
    //bitmap.getConfig()

    try {
        ExifInterface exif = new ExifInterface(imagePath);
        int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);

        Log.v(LCAT, "Orient: " + exifOrientation);

        int rotate = 0;
        switch (exifOrientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            rotate = 90;
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            rotate = 180;
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            rotate = 270;
            break;
        }

        Log.v(LCAT, "Rotation: " + rotate);

        if (rotate != 0) {

            // Getting width & height of the given image.
            int w = bitmap.getWidth();
            int h = bitmap.getHeight();

            // Setting pre rotate
            Matrix mtx = new Matrix();
            mtx.preRotate(rotate);

            // Rotating Bitmap
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
            // tesseract req. ARGB_8888
            bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        }

    } catch (IOException e) {
        Log.e(LCAT, "Rotate or coversion failed: " + e.toString());
    }

    //        ImageView iv = (ImageView) findViewById(R.id.image);
    //        iv.setImageBitmap(bitmap);
    //        iv.setVisibility(View.VISIBLE);

    Log.v(LCAT, "Before baseApi");

    TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.setDebug(true);
    baseApi.init(dataParentPath /*DATA_PATH*/, language);
    baseApi.setImage(bitmap);
    //baseApi.get
    String recognizedText = baseApi.getUTF8Text();
    baseApi.end();

    Log.v(LCAT, "OCR Result: " + recognizedText);

    // clean up and show
    if (language.equalsIgnoreCase("eng")) {
        recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
    }

    return recognizedText.trim();
}

From source file:uk.co.senab.photup.model.PhotoUpload.java

public void detectPhotoTags(final Bitmap originalBitmap) {
    // If we've already done Face detection, don't do it again...
    if (mCompletedDetection) {
        return;/*  w ww. j  a  v a2s.c o m*/
    }

    final OnFaceDetectionListener listener = mFaceDetectListener.get();
    if (null != listener) {
        listener.onFaceDetectionStarted(this);
    }

    final int bitmapWidth = originalBitmap.getWidth();
    final int bitmapHeight = originalBitmap.getHeight();

    Bitmap bitmap = originalBitmap;

    // The Face detector only accepts 565 bitmaps, so create one if needed
    if (Bitmap.Config.RGB_565 != bitmap.getConfig()) {
        bitmap = originalBitmap.copy(Bitmap.Config.RGB_565, false);
    }

    final FaceDetector detector = new FaceDetector(bitmapWidth, bitmapHeight,
            Constants.FACE_DETECTOR_MAX_FACES);
    final FaceDetector.Face[] faces = new FaceDetector.Face[Constants.FACE_DETECTOR_MAX_FACES];
    final int detectedFaces = detector.findFaces(bitmap, faces);

    // We must have created a converted 565 bitmap
    if (bitmap != originalBitmap) {
        bitmap.recycle();
        bitmap = null;
    }

    if (Flags.DEBUG) {
        Log.d(LOG_TAG, "Detected Faces: " + detectedFaces);
    }

    FaceDetector.Face face;
    final PointF point = new PointF();
    for (int i = 0, z = faces.length; i < z; i++) {
        face = faces[i];
        if (null != face) {
            if (Flags.DEBUG) {
                Log.d(LOG_TAG, "Detected Face with confidence: " + face.confidence());
            }
            face.getMidPoint(point);
            addPhotoTag(new PhotoTag(point.x, point.y, bitmapWidth, bitmapWidth));
        }
    }

    if (null != listener) {
        listener.onFaceDetectionFinished(this);
    }
    mFaceDetectListener = null;

    mCompletedDetection = true;
}