mirror of
https://github.com/lovell/sharp.git
synced 2026-02-04 13:46:19 +01:00
Add margin option to trim operation #4480
This commit is contained in:
committed by
Lovell Fuller
parent
d161e45e06
commit
a5e726002c
@@ -285,7 +285,7 @@ namespace sharp {
|
||||
/*
|
||||
Trim an image
|
||||
*/
|
||||
VImage Trim(VImage image, std::vector<double> background, double threshold, bool const lineArt) {
|
||||
VImage Trim(VImage image, std::vector<double> background, double threshold, bool const lineArt, int const margin) {
|
||||
if (image.width() < 3 && image.height() < 3) {
|
||||
throw VError("Image to trim must be at least 3x3 pixels");
|
||||
}
|
||||
@@ -320,18 +320,36 @@ namespace sharp {
|
||||
if (widthA > 0 && heightA > 0) {
|
||||
if (width > 0 && height > 0) {
|
||||
// Combined bounding box (B)
|
||||
int const leftB = std::min(left, leftA);
|
||||
int const topB = std::min(top, topA);
|
||||
int const widthB = std::max(left + width, leftA + widthA) - leftB;
|
||||
int const heightB = std::max(top + height, topA + heightA) - topB;
|
||||
int leftB = std::min(left, leftA);
|
||||
int topB = std::min(top, topA);
|
||||
int widthB = std::max(left + width, leftA + widthA) - leftB;
|
||||
int heightB = std::max(top + height, topA + heightA) - topB;
|
||||
if (margin > 0) {
|
||||
leftB = std::max(0, leftB - margin);
|
||||
topB = std::max(0, topB - margin);
|
||||
widthB = std::min(image.width() - leftB, widthB + 2 * margin);
|
||||
heightB = std::min(image.height() - topB, heightB + 2 * margin);
|
||||
}
|
||||
return image.extract_area(leftB, topB, widthB, heightB);
|
||||
} else {
|
||||
// Use alpha only
|
||||
if (margin > 0) {
|
||||
leftA = std::max(0, leftA - margin);
|
||||
topA = std::max(0, topA - margin);
|
||||
widthA = std::min(image.width() - leftA, widthA + 2 * margin);
|
||||
heightA = std::min(image.height() - topA, heightA + 2 * margin);
|
||||
}
|
||||
return image.extract_area(leftA, topA, widthA, heightA);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (width > 0 && height > 0) {
|
||||
if (margin > 0) {
|
||||
left = std::max(0, left - margin);
|
||||
top = std::max(0, top - margin);
|
||||
width = std::min(image.width() - left, width + 2 * margin);
|
||||
height = std::min(image.height() - top, height + 2 * margin);
|
||||
}
|
||||
return image.extract_area(left, top, width, height);
|
||||
}
|
||||
return image;
|
||||
|
||||
Reference in New Issue
Block a user