1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License
15  */
16 
17 package com.android.settings.wifi.qrcode;
18 
19 import com.google.zxing.LuminanceSource;
20 
21 /**
22  * This helper class implements crop method to crop preview picture.
23  */
24 public class QrYuvLuminanceSource extends LuminanceSource {
25 
26     private byte[] mYuvData;
27     private int mWidth;
28     private int mHeight;
29 
QrYuvLuminanceSource(byte[] yuvData, int width, int height)30     public QrYuvLuminanceSource(byte[] yuvData, int width, int height) {
31         super(width, height);
32 
33         mWidth = width;
34         mHeight = height;
35         mYuvData = yuvData;
36     }
37 
38     @Override
isCropSupported()39     public boolean isCropSupported() {
40         return true;
41     }
42 
43     @Override
crop(int left, int top, int crop_width, int crop_height)44     public LuminanceSource crop(int left, int top, int crop_width, int crop_height) {
45         final byte[] newImage = new byte[crop_width * crop_height];
46         int inputOffset = top * mWidth + left;
47 
48         if (left + crop_width > mWidth || top + crop_height > mHeight) {
49             throw new IllegalArgumentException("cropped rectangle does not fit within image data.");
50         }
51 
52         for (int y = 0; y < crop_height; y++) {
53             System.arraycopy(mYuvData, inputOffset, newImage, y * crop_width, crop_width);
54             inputOffset += mWidth;
55         }
56         return new QrYuvLuminanceSource(newImage, crop_width, crop_height);
57     }
58 
59     @Override
getRow(int y, byte[] row)60     public byte[] getRow(int y, byte[] row) {
61         if (y < 0 || y >= mHeight) {
62             throw new IllegalArgumentException("Requested row is outside the image: " + y);
63         }
64         if (row == null || row.length < mWidth) {
65             row = new byte[mWidth];
66         }
67         System.arraycopy(mYuvData, y * mWidth, row, 0, mWidth);
68         return row;
69     }
70 
71     @Override
getMatrix()72     public byte[] getMatrix() {
73         return mYuvData;
74     }
75 }
76