///|
#derive(Debug)
pub(all) suberror MarkError {
Invalid(String)
Unreadable(String)
RegistrationFailed(String)
ReviewRequired(String)
}
///|
pub struct GrayImage {
width : Int32
height : Int32
pixels : Bytes
}
///|
const PIXEL_LIMIT : Int32 = 12000000
///|
fn checked_pixels(width : Int32, height : Int32) -> Int32 raise MarkError {
if width < 1 || height < 1 || width > 12000 || height > 12000 {
raise Invalid("image dimensions must be between 1 and 12000")
}
let count = width.to_int64() * height.to_int64()
if count > PIXEL_LIMIT.to_int64() {
raise Invalid("image exceeds the 12 megapixel limit")
}
count.to_int()
}
///|
pub fn GrayImage::new(
width : Int32,
height : Int32,
pixels : Bytes,
) -> GrayImage raise MarkError {
if pixels.length() != checked_pixels(width, height) {
raise Invalid("image byte count does not match dimensions")
}
{ width, height, pixels, }
}
///|
pub fn GrayImage::from_rgba(
width : Int32,
height : Int32,
pixels : Bytes,
) -> GrayImage raise MarkError {
let count = checked_pixels(width, height)
if pixels.length() != count * 4 {
raise Invalid("RGBA byte count does not match dimensions")
}
let gray = FixedArray::make(count, b'\x00')
for i in 0.. Int32 {
self.pixels[y * self.width + x].to_int()
}
///|
pub fn GrayImage::get(self : GrayImage, x : Int32, y : Int32) -> Int32? {
if x < 0 || y < 0 || x >= self.width || y >= self.height {
None
} else {
Some(self.pixel(x, y))
}
}
///|
fn GrayImage::interpolate(self : GrayImage, x : Double, y : Double) -> Double? {
if !(x >= 0.0 &&
y >= 0.0 &&
x <= (self.width - 1).to_double() &&
y <= (self.height - 1).to_double()) {
return None
}
let ix = x.to_int()
let iy = y.to_int()
let right = @cmp.minimum(ix + 1, self.width - 1)
let bottom = @cmp.minimum(iy + 1, self.height - 1)
let dx = x - ix.to_double()
let dy = y - iy.to_double()
let top = self.pixel(ix, iy).to_double() * (1.0 - dx) +
self.pixel(right, iy).to_double() * dx
let low = self.pixel(ix, bottom).to_double() * (1.0 - dx) +
self.pixel(right, bottom).to_double() * dx
Some(top * (1.0 - dy) + low * dy)
}
///|
pub fn GrayImage::crop(
self : GrayImage,
x : Int32,
y : Int32,
width : Int32,
height : Int32,
) -> GrayImage raise MarkError {
let count = checked_pixels(width, height)
if x < 0 || y < 0 || x > self.width - width || y > self.height - height {
raise Invalid("crop lies outside image")
}
let data = FixedArray::make(count, b'\x00')
for row in 0.. Int32 {
if n < low {
low
} else if n > high {
high
} else {
n
}
}
///|
fn clamp_unit(n : Double) -> Double {
if n < 0.0 {
0.0
} else if n > 1.0 {
1.0
} else {
n
}
}
///|
pub fn error_message(error : MarkError) -> String {
match error {
Invalid(message) => message
Unreadable(message) => message
RegistrationFailed(message) => message
ReviewRequired(message) => message
}
}