summaryrefslogtreecommitdiff
path: root/mv_barcode/barcode_generator/src/BarcodeGenerator.cpp
blob: 28fd094d9c90789506914b26aac7642b8fc28910 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/**
 * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "BarcodeGenerator.h"

#include <mv_private.h>

#include <zint.h>

#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs/legacy/constants_c.h>

#include <cstring>
#include <vector>
#include <unistd.h>
#include <mv_barcode_generate.h>

#define ZINT_COLOUR_SIZE 10

namespace MediaVision
{
namespace Barcode
{
namespace
{
int getFormatEncodingInfo(BarcodeImageFormat imageFormat, std::vector<std::string> &extensions,
						  std::vector<int> &compressionParams)
{
	static const int PNG_COMPRESSION_LEVEL = 3;

	compressionParams.clear();
	extensions.clear();

	switch (imageFormat) {
	case BARCODE_IMAGE_PNG:
		compressionParams.push_back(CV_IMWRITE_PNG_COMPRESSION);
		compressionParams.push_back(PNG_COMPRESSION_LEVEL);
		extensions.push_back(".png");
		break;
	case BARCODE_IMAGE_JPG:
		extensions.push_back(".jpg");
		extensions.push_back(".jpeg");
		extensions.push_back(".jpe");
		break;
	case BARCODE_IMAGE_BMP:
		extensions.push_back(".bmp");
		extensions.push_back(".dib");
		break;
	default:
		return BARCODE_ERROR_INVALID_OPTION;
	}
	return BARCODE_ERROR_NONE;
}

int createBarcode(const std::string &message, BarcodeType type, BarcodeQREncodingMode encodingMode,
				  BarcodeQRErrorCorrectionLevel correctionLevel, int qrVersion, int showText, char *fgcolour,
				  char *bgcolour, zint_symbol *symbol, Common::EngineConfig *engineCfg)
{
	/* set input values */
	symbol->symbology = type;
	symbol->input_mode = encodingMode;
	symbol->option_1 = correctionLevel;
	symbol->option_2 = qrVersion;
	symbol->scale = 1;
	symbol->show_hrt = showText;

	/* set default values */
	if (fgcolour) {
		std::strncpy(symbol->fgcolour, fgcolour, ZINT_COLOUR_SIZE - 1);
		if (strlen(fgcolour) > 9) {
			symbol->fgcolour[9] = '\0';
		}
	} else {
		std::strncpy(symbol->fgcolour, "000000", ZINT_COLOUR_SIZE - 1);
	}

	if (bgcolour) {
		std::strncpy(symbol->bgcolour, bgcolour, ZINT_COLOUR_SIZE - 1);
		if (strlen(bgcolour) > 9) {
			symbol->bgcolour[9] = '\0';
		}
	} else {
		std::strncpy(symbol->bgcolour, "ffffff", ZINT_COLOUR_SIZE - 1);
	}

	LOGI("Check colors: front %s, back %s", symbol->fgcolour, symbol->bgcolour);

	symbol->border_width = 1;
	symbol->height = 50;

	if (engineCfg) {
		int value;
		int ret = engineCfg->getIntegerAttribute(MV_BARCODE_GENERATE_ATTR_DATA_SHAPE, &value);

		if (ret == MEDIA_VISION_ERROR_NONE) {
			switch (value) {
			case MV_BARCODE_GENERATE_ATTR_SHAPE_CIRCLE:
				symbol->output_options |= BARCODE_DATA_CIRCLE;
				break;

			default:
				break;
			}
		}

		ret = engineCfg->getIntegerAttribute(MV_BARCODE_GENERATE_ATTR_FINDER_SHAPE, &value);

		if (ret == MEDIA_VISION_ERROR_NONE) {
			switch (value) {
			case MV_BARCODE_GENERATE_ATTR_SHAPE_ROUND_RECT:
				symbol->output_options |= BARCODE_FINDER_ROUNDRECT;
				break;
			case MV_BARCODE_GENERATE_ATTR_SHAPE_CIRCLE:
				symbol->output_options |= BARCODE_FINDER_CIRCLE;
				break;

			default:
				break;
			}
		}
	}

	if (type == BARCODE_QR) {
		symbol->whitespace_width = 0;
	} else {
		symbol->whitespace_width = 10;
	}

	/* create barcode */
	const int rotationAngle = 0;
	int error =
			ZBarcode_Encode_and_Buffer(symbol, (unsigned char *) (message.c_str()), message.length(), rotationAngle);

	return error;
}

static int __write_buffer_to_img(zint_symbol *symbol, const std::string &imageFileName, BarcodeImageFormat imageFormat,
								 const int imageWidth, const int imageHeight, const std::string &logoPath)
{
	if (imageWidth <= 0 || imageHeight <= 0) {
		LOGE("Barcode image size is invalid: %i x %i. Terminate write to "
			 "the image operation",
			 imageWidth, imageHeight);
		return BARCODE_ERROR_INVALID_DATA;
	}

	/* find directory */
	std::string prefix_imageFileName = imageFileName.substr(0, imageFileName.find_last_of('/'));
	LOGD("prefix_path: %s", prefix_imageFileName.c_str());

	/* check the directory is available */
	if (access(prefix_imageFileName.c_str(), F_OK)) {
		LOGE("Can't save barcode image to the path. The path[%s] doesn't existed.", prefix_imageFileName.c_str());
		return BARCODE_ERROR_INVALID_PATH;
	}

	/* check current extension */
	std::vector<std::string> expectedExtensions;
	std::vector<int> compressionParams;

	int error = getFormatEncodingInfo(imageFormat, expectedExtensions, compressionParams);

	if (BARCODE_ERROR_NONE != error || expectedExtensions.empty()) {
		LOGE("Image format is incorrectly specified or not supported");
		return error;
	}

	bool rightExtensionFlag = false;

	std::string resultFilePath(imageFileName);

	for (size_t extNum = 0; extNum < expectedExtensions.size(); ++extNum) {
		if (resultFilePath.size() >= expectedExtensions[extNum].size()) {
			std::string givenExtension = resultFilePath.substr(
					resultFilePath.length() - expectedExtensions[extNum].size(), expectedExtensions[extNum].size());

			std::transform(givenExtension.begin(), givenExtension.end(), givenExtension.begin(), ::tolower);

			if (givenExtension == expectedExtensions[extNum]) {
				rightExtensionFlag = true;
				break;
			}
		}
	}

	if (!rightExtensionFlag)
		resultFilePath += expectedExtensions[0];

	cv::Mat image(symbol->bitmap_height, symbol->bitmap_width, CV_8UC3, symbol->bitmap);
	cv::resize(image, image, cv::Size(imageWidth, imageHeight), 0, 0, cv::INTER_AREA);

	if (!logoPath.empty()) {
		cv::Mat logo = cv::imread(logoPath.c_str(), cv::IMREAD_COLOR);
		cv::resize(logo, logo, cv::Size(imageWidth / 5, imageHeight / 5), 0, 0, cv::INTER_AREA);
		logo.copyTo(image(cv::Rect(2 * logo.cols, 2 * logo.rows, logo.cols, logo.rows)));
	}

	error = cv::imwrite(resultFilePath, image, compressionParams) ? BARCODE_ERROR_NONE : BARCODE_ERROR_INVALID_DATA;

	if (BARCODE_ERROR_NONE != error) {
		LOGE("Write barcode image to file %s operation failed.", resultFilePath.c_str());
		return error;
	}

	return error;
}

} /* anonymous namespace */

int BarcodeGenerator::generateBarcodeToImage(const std::string &imageFileName, BarcodeImageFormat imageFormat,
											 const int imageWidth, const int imageHeight, const std::string &message,
											 BarcodeType type, Common::EngineConfig *engineCfg,
											 BarcodeQREncodingMode encodingMode,
											 BarcodeQRErrorCorrectionLevel correctionLevel, int qrVersion, int showText,
											 char *fgcolour, char *bgcolour)
{
	zint_symbol *symbol = ZBarcode_Create();

	if (symbol == NULL) {
		LOGE("ZBarcode creation failed");
		return BARCODE_ERROR_ENCODING_PROBLEM;
	}

	std::string logoPath;
	int error = createBarcode(message, type, encodingMode, correctionLevel, qrVersion, showText, fgcolour, bgcolour,
							  symbol, engineCfg);

	if (error != BARCODE_ERROR_NONE) {
		LOGE("Barcode creation failed, clean memory");
		goto zbarcode_delete;
	}

	if (engineCfg) {
		error = engineCfg->getStringAttribute(std::string(MV_BARCODE_GENERATE_ATTR_EMBED_IMG_PATH), &logoPath);
		if (error != BARCODE_ERROR_NONE) {
			LOGE("getStringAttribute failed error : %d", error);
			goto zbarcode_delete;
		}
	}

	error = __write_buffer_to_img(symbol, imageFileName, imageFormat, imageWidth, imageHeight, logoPath);
	if (error != BARCODE_ERROR_NONE)
		LOGE("Barcode [%s] file write fail, clean memory", imageFileName.c_str());
	else
		LOGI("Barcode image [%s] is successfully generated, clean memory", imageFileName.c_str());

zbarcode_delete:
	ZBarcode_Delete(symbol);
	return error;
}

int BarcodeGenerator::generateBarcodeToBuffer(unsigned char **imageBuffer, unsigned int *imageWidth,
											  unsigned int *imageHeight, unsigned int *imageChannels,
											  const std::string &message, BarcodeType type,
											  Common::EngineConfig *engineCfg, BarcodeQREncodingMode encodingMode,
											  BarcodeQRErrorCorrectionLevel correctionLevel, int qrVersion,
											  int showText, char *fgcolour, char *bgcolour)
{
	zint_symbol *symbol = ZBarcode_Create();

	if (symbol == NULL) {
		LOGE("ZBarcode creation failed");

		return BARCODE_ERROR_ENCODING_PROBLEM;
	}

	int error = createBarcode(message, type, encodingMode, correctionLevel, qrVersion, showText, fgcolour, bgcolour,
							  symbol, engineCfg);

	if (error != BARCODE_ERROR_NONE) {
		LOGE("Barcode creation failed, clean memory");
		ZBarcode_Delete(symbol);
		return error;
	}

	/* fill output buffer */
	*imageWidth = symbol->bitmap_width;
	*imageHeight = symbol->bitmap_height;
	*imageChannels = 3;
	const unsigned int imageBufferSize = (*imageWidth) * (*imageHeight) * (*imageChannels);
	*imageBuffer = new unsigned char[imageBufferSize];
	memmove(*imageBuffer, symbol->bitmap, imageBufferSize);

	LOGI("Barcode buffer has been successfully generated, clean memory");
	ZBarcode_Delete(symbol);

	return BARCODE_ERROR_NONE;
}

} /* Barcode */
} /* MediaVision */