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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
/*
* Copyright 2007 ZXing authors
*
* 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.
*/
// package com.google.zxing.common;
// import java.util.Arrays;
use std::fmt;
use crate::common::Result;
use crate::{point_f, point_i, Exceptions, Point};
use super::BitArray;
/**
* <p>Represents a 2D matrix of bits. In function arguments below, and throughout the common
* module, x is the column position, and y is the row position. The ordering is always x, y.
* The origin is at the top-left.</p>
*
* <p>Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins
* with a new int. This is done intentionally so that we can copy out a row into a BitArray very
* efficiently.</p>
*
* <p>The ordering of bits is row-major. Within each int, the least significant bits are used first,
* meaning they represent lower x values. This is compatible with BitArray's implementation.</p>
*
* @author Sean Owen
* @author dswitkin@google.com (Daniel Switkin)
*/
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BitMatrix {
width: u32,
height: u32,
row_size: usize,
bits: Vec<u32>,
}
impl BitMatrix {
/**
* Creates an empty square {@code BitMatrix}.
*
* @param dimension height and width
*/
pub fn with_single_dimension(dimension: u32) -> Result<Self> {
Self::new(dimension, dimension)
}
/**
* Creates an empty {@code BitMatrix}.
*
* @param width bit matrix width
* @param height bit matrix height
*/
pub fn new(width: u32, height: u32) -> Result<Self> {
if width < 1 || height < 1 {
return Err(Exceptions::illegal_argument_with(
"Both dimensions must be greater than 0",
));
}
Ok(Self {
width,
height,
row_size: ((width + 31) / 32) as usize,
bits: vec![0; (((width + 31) / 32) * height) as usize],
})
// this.width = width;
// this.height = height;
// this.rowSize = (width + 31) / 32;
// bits = new int[rowSize * height];
}
#[allow(dead_code)]
fn with_all_data(&self, width: u32, height: u32, rowSize: usize, bits: Vec<u32>) -> Self {
Self {
width,
height,
row_size: rowSize,
bits,
}
}
/**
* Interprets a 2D array of booleans as a {@code BitMatrix}, where "true" means an "on" bit.
*
* @param image bits of the image, as a row-major 2D array. Elements are arrays representing rows
* @return {@code BitMatrix} representation of image
*/
pub fn parse_bools(image: &Vec<Vec<bool>>) -> Self {
let height: u32 = image.len().try_into().unwrap();
let width: u32 = image[0].len().try_into().unwrap();
let mut bits = BitMatrix::new(width, height).unwrap();
for (i, imageI) in image.iter().enumerate().take(height as usize) {
// for i in 0..height as usize {
//for (int i = 0; i < height; i++) {
// let imageI = &image[i];
for (j, imageI_j) in imageI.iter().enumerate().take(width as usize) {
// for j in 0..width as usize {
//for (int j = 0; j < width; j++) {
if *imageI_j {
bits.set(j as u32, i as u32);
}
}
}
bits
}
pub fn parse_strings(
string_representation: &str,
set_string: &str,
unset_string: &str,
) -> Result<Self> {
// cannot pass nulls in rust
// if (stringRepresentation == null) {
// throw new IllegalArgumentException();
// }
let mut bits = vec![false; string_representation.chars().count()];
let mut bitsPos = 0;
let mut rowStartPos = 0;
let mut rowLength = 0; //-1;
let mut first_run = true;
let mut nRows = 0;
let mut pos = 0;
while pos < string_representation.chars().count() {
if string_representation
.chars()
.nth(pos)
.ok_or(Exceptions::ILLEGAL_STATE)?
== '\n'
|| string_representation
.chars()
.nth(pos)
.ok_or(Exceptions::ILLEGAL_STATE)?
== '\r'
{
if bitsPos > rowStartPos {
//if rowLength == -1 {
if first_run {
first_run = false;
rowLength = bitsPos - rowStartPos;
} else if bitsPos - rowStartPos != rowLength {
return Err(Exceptions::illegal_argument_with(
"row lengths do not match",
));
}
rowStartPos = bitsPos;
nRows += 1;
}
pos += 1;
} else if string_representation[pos..].starts_with(set_string) {
pos += set_string.len();
bits[bitsPos] = true;
bitsPos += 1;
} else if string_representation[pos..].starts_with(unset_string) {
pos += unset_string.len();
bits[bitsPos] = false;
bitsPos += 1;
} else {
return Err(Exceptions::illegal_argument_with(format!(
"illegal character encountered: {}",
string_representation[pos..].to_owned()
)));
}
}
// no EOL at end?
if bitsPos > rowStartPos {
//if rowLength == -1 {
if first_run {
// first_run = false;
rowLength = bitsPos - rowStartPos;
} else if bitsPos - rowStartPos != rowLength {
return Err(Exceptions::illegal_argument_with(
"row lengths do not match",
));
}
nRows += 1;
}
let mut matrix = BitMatrix::new(rowLength as u32, nRows)?;
for (i, bit) in bits.iter().enumerate().take(bitsPos) {
// for i in 0..bitsPos {
//for (int i = 0; i < bitsPos; i++) {
if *bit {
matrix.set((i % rowLength) as u32, (i / rowLength) as u32);
}
}
Ok(matrix)
}
/**
* Gets the requested bit, where true means black.
*
* x The horizontal component (i.e. which column)
* y The vertical component (i.e. which row)
* returns the value of given bit in matrix, or false if the requested point is out of bounds of the image
*/
pub fn get(&self, x: u32, y: u32) -> bool {
let offset = self.get_offset(y, x);
if offset >= self.bits.len() {
return false;
}
((self.bits[offset] >> (x & 0x1f)) & 1) != 0
}
pub fn get_point(&self, point: Point) -> bool {
self.get(point.x as u32, point.y as u32)
// let offset = self.get_offset(point.y as u32, point.x as u32);
// ((self.bits[offset] >> (x & 0x1f)) & 1) != 0
}
pub fn get_index<T: Into<usize>>(&self, index: T) -> bool {
self.get_point(self.calculate_point_from_index(index.into()))
}
#[inline(always)]
fn calculate_point_from_index(&self, index: usize) -> Point {
let row = index / (self.getWidth() as usize);
let column = index % (self.getWidth() as usize);
point_i(column as u32, row as u32)
}
#[inline(always)]
fn get_offset(&self, y: u32, x: u32) -> usize {
y as usize * self.row_size + (x as usize / 32)
}
pub fn try_get(&self, x: u32, y: u32) -> Option<bool> {
let offset = self.get_offset(y, x);
if offset >= self.bits.len() {
return None;
}
Some(((self.bits[offset] >> (x & 0x1f)) & 1) != 0)
}
pub fn try_get_point(&self, point: Point) -> Option<bool> {
self.try_get(point.x as u32, point.y as u32)
}
pub fn try_get_area(&self, x: u32, y: u32, box_size: u32) -> Option<bool> {
let mut matrix = Vec::with_capacity((box_size * box_size) as usize);
let start_x = (x as i32 - box_size as i32 / 2).max(0) as u32;
let end_x = x + box_size / 2;
let start_y = (y as i32 - box_size as i32 / 2).max(0) as u32;
let end_y = y + box_size / 2;
for get_x in start_x..=end_x {
for get_y in start_y..=end_y {
matrix.push(self.try_get(get_x, get_y)?);
}
}
let total_set = matrix.iter().filter(|bit| **bit).count();
if (total_set as f32 / matrix.len() as f32) >= 0.5 {
Some(true)
} else {
Some(false)
}
}
/// Confusingly returns true if the requested element is out of bounds
pub fn check_in_bounds(&self, x: u32, y: u32) -> bool {
(self.get_offset(y, x)) >= self.bits.len()
}
/// Confusingly returns true if the requested element is out of bounds
pub fn check_point_in_bounds(&self, point: Point) -> bool {
self.check_in_bounds(point.x as u32, point.y as u32)
}
/**
* <p>Sets the given bit to true.</p>
*
* @param x The horizontal component (i.e. which column)
* @param y The vertical component (i.e. which row)
*/
pub fn set(&mut self, x: u32, y: u32) {
let offset = self.get_offset(y, x);
self.bits[offset] |= 1 << (x & 0x1f);
}
pub fn set_bool(&mut self, x: u32, y: u32, value: bool) {
if value {
self.set(x, y)
} else {
self.unset(x, y)
}
}
pub fn unset(&mut self, x: u32, y: u32) {
let offset = self.get_offset(y, x);
self.bits[offset] &= !(1 << (x & 0x1f));
}
/**
* <p>Flips the given bit.</p>
*
* @param x The horizontal component (i.e. which column)
* @param y The vertical component (i.e. which row)
*/
pub fn flip_coords(&mut self, x: u32, y: u32) {
let offset = self.get_offset(y, x);
self.bits[offset] ^= 1 << (x & 0x1f);
}
/**
* <p>Flips every bit in the matrix.</p>
*/
pub fn flip_self(&mut self) {
let max = self.bits.len();
for bit_set in self.bits.iter_mut().take(max) {
*bit_set = !*bit_set;
}
}
/**
* Exclusive-or (XOR): Flip the bit in this {@code BitMatrix} if the corresponding
* mask bit is set.
*
* @param mask XOR mask
*/
pub fn xor(&mut self, mask: &BitMatrix) -> Result<()> {
if self.width != mask.width || self.height != mask.height || self.row_size != mask.row_size
{
return Err(Exceptions::illegal_argument_with(
"input matrix dimensions do not match",
));
}
// let mut rowArray = BitArray::with_size(self.width as usize);
for y in 0..self.height {
//for (int y = 0; y < height; y++) {
let offset = y as usize * self.row_size;
let rowArray = mask.getRow(y);
let row = rowArray.getBitArray();
for (x, row_x) in row.iter().enumerate().take(self.row_size) {
// for x in 0..self.row_size {
//for (int x = 0; x < rowSize; x++) {
self.bits[offset + x] ^= *row_x;
}
}
Ok(())
}
/**
* Clears all bits (sets to false).
*/
pub fn clear(&mut self) {
// let max = self.bits.len();
// for i in 0..max {
// //for (int i = 0; i < max; i++) {
// self.bits[i] = 0;
// }
self.bits.fill(0);
}
/**
* <p>Sets a square region of the bit matrix to true.</p>
*
* @param left The horizontal position to begin at (inclusive)
* @param top The vertical position to begin at (inclusive)
* @param width The width of the region
* @param height The height of the region
*/
pub fn setRegion(&mut self, left: u32, top: u32, width: u32, height: u32) -> Result<()> {
// if top < 0 || left < 0 {
// return Err(Exceptions::IllegalArgumentException(
// "Left and top must be nonnegative".to_owned(),
// ));
// }
if height < 1 || width < 1 {
return Err(Exceptions::illegal_argument_with(
"height and width must be at least 1",
));
}
let right = left + width;
let bottom = top + height;
if bottom > self.height || right > self.width {
return Err(Exceptions::illegal_argument_with(
"the region must fit inside the matrix",
));
}
for y in top..bottom {
//for (int y = top; y < bottom; y++) {
let offset = y as usize * self.row_size;
for x in left..right {
//for (int x = left; x < right; x++) {
self.bits[offset + (x as usize / 32)] |= 1 << (x & 0x1f);
}
}
Ok(())
}
/**
* A fast method to retrieve one row of data from the matrix as a BitArray.
*
* @param y The row to retrieve
* @param row An optional caller-allocated BitArray, will be allocated if null or too small
* @return The resulting BitArray - this reference should always be used even when passing
* your own row
*/
pub fn getRow(&self, y: u32) -> BitArray {
// let mut rw: BitArray = if row.getSize() < self.width as usize {
// BitArray::with_size(self.width as usize)
// } else {
// let mut z = row; //row.clone();
// z.clear();
// z
// // row.clear();
// // row.clone()
// };
let mut rw = BitArray::with_size(self.width as usize);
let offset = y as usize * self.row_size;
for x in 0..self.row_size {
//for (int x = 0; x < rowSize; x++) {
rw.setBulk(x * 32, self.bits[offset + x]);
}
rw
}
/// This method returns a column of the bitmatrix.
///
/// The current implementation may be very slow.
pub fn getCol(&self, x: u32) -> BitArray {
let mut cw = BitArray::with_size(self.height as usize);
for y in 0..self.height {
if self.get(x, y) {
cw.set(y as usize)
}
}
cw
}
/**
* @param y row to set
* @param row {@link BitArray} to copy from
*/
pub fn setRow(&mut self, y: u32, row: &BitArray) {
self.bits[y as usize * self.row_size..y as usize * self.row_size + self.row_size]
.clone_from_slice(&row.getBitArray()[0..self.row_size])
//System.arraycopy(row.getBitArray(), 0, self.bits, y * self.rowSize, self.rowSize);
}
/**
* Modifies this {@code BitMatrix} to represent the same but rotated the given degrees (0, 90, 180, 270)
*
* @param degrees number of degrees to rotate through counter-clockwise (0, 90, 180, 270)
*/
pub fn rotate(&mut self, degrees: u32) -> Result<()> {
match degrees % 360 {
0 => Ok(()),
90 => {
self.rotate90();
Ok(())
}
180 => {
self.rotate180();
Ok(())
}
270 => {
self.rotate90();
self.rotate180();
Ok(())
}
_ => Err(Exceptions::illegal_argument_with(
"degrees must be a multiple of 0, 90, 180, or 270",
)),
}
}
/**
* Modifies this {@code BitMatrix} to represent the same but rotated 180 degrees
*/
pub fn rotate180(&mut self) {
// let mut topRow = BitArray::with_size(self.width as usize);
// let mut bottomRow = BitArray::with_size(self.width as usize);
let maxHeight = (self.height + 1) / 2;
for i in 0..maxHeight {
//for (int i = 0; i < maxHeight; i++) {
let mut topRow = self.getRow(i);
let bottomRowIndex = self.height - 1 - i;
let mut bottomRow = self.getRow(bottomRowIndex);
topRow.reverse();
bottomRow.reverse();
self.setRow(i, &bottomRow);
self.setRow(bottomRowIndex, &topRow);
}
}
/**
* Modifies this {@code BitMatrix} to represent the same but rotated 90 degrees counterclockwise
*/
pub fn rotate90(&mut self) {
let newWidth = self.height;
let newHeight = self.width;
let newRowSize = (newWidth + 31) / 32;
let mut newBits = vec![0; (newRowSize * newHeight) as usize];
for y in 0..self.height {
//for (int y = 0; y < height; y++) {
for x in 0..self.width {
//for (int x = 0; x < width; x++) {
let offset = self.get_offset(y, x);
if ((self.bits[offset] >> (x & 0x1f)) & 1) != 0 {
let newOffset: usize = ((newHeight - 1 - x) * newRowSize + (y / 32)) as usize;
newBits[newOffset] |= 1 << (y & 0x1f);
}
}
}
self.width = newWidth;
self.height = newHeight;
self.row_size = newRowSize as usize;
self.bits = newBits;
}
/**
* This is useful in detecting the enclosing rectangle of a 'pure' barcode.
*
* @return {@code left,top,width,height} enclosing rectangle of all 1 bits, or null if it is all white
*/
pub fn getEnclosingRectangle(&self) -> Option<[u32; 4]> {
let mut left = self.width;
let mut top = self.height;
// let right = -1;
// let bottom = -1;
let mut right: u32 = 0;
let mut bottom = 0;
for y in 0..self.height {
//for (int y = 0; y < height; y++) {
for x32 in 0..self.row_size {
//for (int x32 = 0; x32 < rowSize; x32++) {
let theBits = self.bits[y as usize * self.row_size + x32];
if theBits != 0 {
if y < top {
top = y;
}
if y > bottom {
bottom = y;
}
if x32 * 32 < left as usize {
let mut bit = 0;
while (theBits << (31 - bit)) == 0 {
bit += 1;
}
if (x32 * 32 + bit) < left as usize {
left = (x32 * 32 + bit) as u32;
}
}
if x32 * 32 + 31 > right as usize {
let mut bit = 31;
while (theBits >> bit) == 0 {
bit -= 1;
}
if (x32 * 32 + bit) > right as usize {
right = (x32 * 32 + bit) as u32;
}
}
}
}
}
if right < left || bottom < top {
return None;
}
Some([left, top, right - left + 1, bottom - top + 1])
}
/**
* This is useful in detecting a corner of a 'pure' barcode.
*
* @return {@code x,y} coordinate of top-left-most 1 bit, or null if it is all white
*/
pub fn getTopLeftOnBit(&self) -> Option<Point> {
let mut bitsOffset = 0;
while bitsOffset < self.bits.len() && self.bits[bitsOffset] == 0 {
bitsOffset += 1;
}
if bitsOffset == self.bits.len() {
return None;
}
let y = bitsOffset / self.row_size;
let mut x = (bitsOffset % self.row_size) * 32;
let theBits = self.bits[bitsOffset];
let mut bit = 0;
while (theBits << (31 - bit)) == 0 {
bit += 1;
}
x += bit;
Some(point_f(x as f32, y as f32))
}
pub fn getBottomRightOnBit(&self) -> Option<Point> {
let mut bitsOffset = self.bits.len() as i64 - 1;
while bitsOffset >= 0 && self.bits[bitsOffset as usize] == 0 {
bitsOffset -= 1;
}
if bitsOffset < 0 {
return None;
}
let y = bitsOffset as usize / self.row_size;
let mut x = (bitsOffset as usize % self.row_size) * 32;
let theBits = self.bits[bitsOffset as usize];
let mut bit = 31;
while (theBits >> bit) == 0 {
bit -= 1;
}
x += bit;
Some(point_f(x as f32, y as f32))
}
/**
* @return The width of the matrix
*/
pub fn getWidth(&self) -> u32 {
self.width()
}
pub fn width(&self) -> u32 {
self.width
}
/**
* @return The height of the matrix
*/
pub fn getHeight(&self) -> u32 {
self.height()
}
pub fn height(&self) -> u32 {
self.height
}
/**
* @return The row size of the matrix
*/
pub fn getRowSize(&self) -> usize {
self.row_size
}
// @Override
// public boolean equals(Object o) {
// if (!(o instanceof BitMatrix)) {
// return false;
// }
// BitMatrix other = (BitMatrix) o;
// return width == other.width && height == other.height && rowSize == other.rowSize &&
// Arrays.equals(bits, other.bits);
// }
// @Override
// public int hashCode() {
// int hash = width;
// hash = 31 * hash + width;
// hash = 31 * hash + height;
// hash = 31 * hash + rowSize;
// hash = 31 * hash + Arrays.hashCode(bits);
// return hash;
// }
/**
* @param setString representation of a set bit
* @param unsetString representation of an unset bit
* @return string representation of entire matrix utilizing given strings
*/
pub fn toString(&self, setString: &str, unsetString: &str) -> String {
self.buildToString(setString, unsetString, "\n")
}
/**
* @param setString representation of a set bit
* @param unsetString representation of an unset bit
* @param lineSeparator newline character in string representation
* @return string representation of entire matrix utilizing given strings and line separator
* @deprecated call {@link #toString(String,String)} only, which uses \n line separator always
*/
// @Deprecated
// public String toString(String setString, String unsetString, String lineSeparator) {
// return buildToString(setString, unsetString, lineSeparator);
// }
fn buildToString(&self, setString: &str, unsetString: &str, lineSeparator: &str) -> String {
let mut result =
String::with_capacity((self.height * (self.width + 1)).try_into().unwrap());
for y in 0..self.height {
//for (int y = 0; y < height; y++) {
for x in 0..self.width {
//for (int x = 0; x < width; x++) {
result.push_str(if self.get(x, y) {
setString
} else {
unsetString
});
}
result.push_str(lineSeparator);
}
result
}
// @Override
// public BitMatrix clone() {
// return new BitMatrix(width, height, rowSize, bits.clone());
// }
// pub fn crop(&self, top:usize, left:usize, height: usize, width: usize) -> BitMatrix {
// let area = self.bits.iter().skip(self.row_size * top).take(self.row_size * height)
// .copied().collect::<Vec<u32>>();
// let new_bits = area.chunks(self.row_size)
// .skip(left).take(width).flatten().copied().collect::<Vec<u32>>();
// Self { width: width, height: height, row_size: width, bits: () }
// }
pub fn crop(&self, top: usize, left: usize, height: usize, width: usize) -> BitMatrix {
let mut new_bm = BitMatrix::new(width as u32, height as u32).expect("create empty");
for y in top..top + height {
// let row = self.getRow(y as u32);
for x in left..left + width {
if self.get(x as u32, y as u32) {
new_bm.set(x as u32, y as u32)
}
}
}
new_bm
}
pub fn is_in(&self, p: Point) -> bool {
self.isIn(p, 0)
}
pub fn isIn(&self, p: Point, b: i32) -> bool {
b as f32 <= p.x
&& p.x < self.getWidth() as f32 - b as f32
&& b as f32 <= p.y
&& p.y < self.getHeight() as f32 - b as f32
}
}
impl fmt::Display for BitMatrix {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.toString("X ", " "))
}
}
impl From<&BitMatrix> for Vec<bool> {
fn from(value: &BitMatrix) -> Self {
let mut arr = vec![false; (value.width * value.height) as usize];
for x in 0..value.width {
for y in 0..value.height {
let insert_pos = ((y * value.width) + x) as usize;
arr[insert_pos] = value.get(x, y);
}
}
arr
}
}
#[cfg(feature = "image")]
/// This should only be used if you *know* that the `DynamicImage` is binary.
impl TryFrom<image::DynamicImage> for BitMatrix {
type Error = Exceptions;
fn try_from(value: image::DynamicImage) -> Result<Self, Self::Error> {
let mut new_bitmatrix = BitMatrix::new(value.width(), value.height())?;
for (x, y, value) in value.as_luma8().unwrap().enumerate_pixels() {
if value.0[0] != u8::MAX {
new_bitmatrix.set(x, y)
}
}
Ok(new_bitmatrix)
}
}
#[cfg(feature = "image")]
impl From<BitMatrix> for image::DynamicImage {
fn from(value: BitMatrix) -> Self {
(&value).into()
}
}
#[cfg(feature = "image")]
impl From<&BitMatrix> for image::DynamicImage {
fn from(value: &BitMatrix) -> Self {
let mut pixels = image::ImageBuffer::new(value.width, value.height);
for (x, y, pixel) in pixels.enumerate_pixels_mut() {
let new_pixel = if value.get(x, y) {
image::Rgb([0, 0, 0])
} else {
image::Rgb([u8::MAX, u8::MAX, u8::MAX])
};
*pixel = new_pixel
}
pixels.into()
}
}
#[cfg(feature = "svg_write")]
impl From<&BitMatrix> for svg::Document {
fn from(value: &BitMatrix) -> Self {
let block_size = 1;
let mut document = svg::Document::new().set(
"viewBox",
(0, 0, value.width * block_size, value.height * block_size),
);
for x in 0..value.width {
for y in 0..value.height {
if value.get(x, y) {
let block = svg::node::element::Rectangle::new()
.set("x", x * block_size)
.set("y", y * block_size)
.set("width", block_size)
.set("height", block_size);
document = document.add(block);
}
}
}
document
}
}