1+ /*
2+ * Copyright (C) 2018-2023 Zebra Technologies Corp
3+ * All rights reserved.
4+ */
5+ package com .zebra .freeformocrsample1 ;
6+
7+ import android .graphics .Bitmap ;
8+ import android .graphics .BitmapFactory ;
9+ import android .graphics .ImageFormat ;
10+ import android .graphics .Matrix ;
11+ import android .graphics .Rect ;
12+ import android .graphics .YuvImage ;
13+
14+ import java .io .ByteArrayOutputStream ;
15+
16+ public class ImageProcessing {
17+
18+ private final String IMG_FORMAT_YUV = "YUV" ;
19+ private final String IMG_FORMAT_Y8 = "Y8" ;
20+
21+ private static ImageProcessing instance = null ;
22+
23+ public static ImageProcessing getInstance () {
24+
25+ if (instance == null ) {
26+ instance = new ImageProcessing ();
27+ }
28+ return instance ;
29+ }
30+
31+ private ImageProcessing () {
32+ //Private Constructor
33+ }
34+
35+ public Bitmap getBitmap (byte [] data , String imageFormat , int orientation , int stride , int width , int height )
36+ {
37+ if (imageFormat .equalsIgnoreCase (IMG_FORMAT_YUV ))
38+ {
39+ ByteArrayOutputStream out = new ByteArrayOutputStream ();
40+ YuvImage yuvImage = new YuvImage (data , ImageFormat .NV21 , width , height , new int []{stride , stride });
41+ yuvImage .compressToJpeg (new Rect (0 , 0 , stride , height ), 100 , out );
42+ yuvImage .getYuvData ();
43+ byte [] imageBytes = out .toByteArray ();
44+ if (orientation != 0 )
45+ {
46+ Matrix matrix = new Matrix ();
47+ matrix .postRotate (orientation );
48+ Bitmap bitmap = BitmapFactory .decodeByteArray (imageBytes , 0 , imageBytes .length );
49+ return Bitmap .createBitmap (bitmap , 0 , 0 , bitmap .getWidth (), bitmap .getHeight (), matrix , true );
50+ }
51+ else
52+ {
53+ return BitmapFactory .decodeByteArray (imageBytes , 0 , imageBytes .length );
54+ }
55+ }
56+ else if (imageFormat .equalsIgnoreCase (IMG_FORMAT_Y8 ))
57+ {
58+ return convertYtoJPG_CPU (data , orientation , stride , height );
59+ }
60+
61+ return null ;
62+ }
63+
64+
65+ private Bitmap convertYtoJPG_CPU (byte [] data , int orientation , int stride , int height )
66+ {
67+ int mLength = data .length ;
68+ int [] pixels = new int [mLength ];
69+ for (int i = 0 ; i < mLength ; i ++)
70+ {
71+ int p = data [i ] & 0xFF ;
72+ pixels [i ] = 0xff000000 | p << 16 | p << 8 | p ;
73+ }
74+ if (orientation != 0 )
75+ {
76+ Matrix matrix = new Matrix ();
77+ matrix .postRotate (orientation );
78+ Bitmap bitmap = Bitmap .createBitmap (pixels , stride , height , Bitmap .Config .ARGB_8888 );
79+ return Bitmap .createBitmap (bitmap , 0 , 0 , bitmap .getWidth (), bitmap .getHeight (), matrix , true );
80+ }
81+ else
82+ {
83+ return Bitmap .createBitmap (pixels , stride , height , Bitmap .Config .ARGB_8888 );
84+ }
85+ }
86+
87+ }
0 commit comments