Removed as many exceptions as possible from the C++ product readers
[zxing.git] / cpp / core / src / zxing / common / GreyscaleLuminanceSource.cpp
1 /*
2  *  GreyscaleLuminanceSource.cpp
3  *  zxing
4  *
5  *  Copyright 2010 ZXing authors All rights reserved.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 #include <zxing/common/GreyscaleLuminanceSource.h>
21 #include <zxing/common/GreyscaleRotatedLuminanceSource.h>
22 #include <zxing/common/IllegalArgumentException.h>
23
24 namespace zxing {
25
26 GreyscaleLuminanceSource::GreyscaleLuminanceSource(unsigned char* greyData, int dataWidth,
27     int dataHeight, int left, int top, int width, int height) : greyData_(greyData),
28     dataWidth_(dataWidth), dataHeight_(dataHeight), left_(left), top_(top), width_(width),
29     height_(height) {
30
31   if (left + width > dataWidth || top + height > dataHeight || top < 0 || left < 0) {
32     throw IllegalArgumentException("Crop rectangle does not fit within image data.");
33   }
34 }
35
36 unsigned char* GreyscaleLuminanceSource::getRow(int y, unsigned char* row) {
37   if (y < 0 || y >= this->getHeight()) {
38     throw IllegalArgumentException("Requested row is outside the image: " + y);
39   }
40   int width = getWidth();
41   // TODO(flyashi): determine if row has enough size.
42   if (row == NULL) {
43     row = new unsigned char[width_];
44   }
45   int offset = (y + top_) * dataWidth_ + left_;
46   memcpy(row, &greyData_[offset], width);
47   return row;
48 }
49
50 unsigned char* GreyscaleLuminanceSource::getMatrix() {
51   if (left_ != 0 || top_ != 0 || dataWidth_ != width_ || dataHeight_ != height_) {
52     unsigned char* cropped = new unsigned char[width_ * height_];
53     for (int row = 0; row < height_; row++) {
54       memcpy(cropped + row * width_, greyData_ + (top_ + row) * dataWidth_ + left_, width_);
55     }
56     return cropped;
57   }
58   return greyData_;
59 }
60
61 Ref<LuminanceSource> GreyscaleLuminanceSource::rotateCounterClockwise() {
62   // Intentionally flip the left, top, width, and height arguments as needed. dataWidth and
63   // dataHeight are always kept unrotated.
64   return Ref<LuminanceSource> (new GreyscaleRotatedLuminanceSource(greyData_, dataWidth_,
65       dataHeight_, top_, left_, height_, width_));
66 }
67
68 } /* namespace */