英文:
How do I filter images that exceeds an aspect ratio
问题
我正在尝试创建一个C#程序,该程序会获取一个目录路径,并对图像进行迭代,然后对于每个图像,它应该检查该图像是否适用于Instagram帖子,而且我不需要裁剪它。
关于Instagram帖子比例的一些信息:
- 正方形:1:1
- 竖直:4:5
- 水平:1.91:1
我正在使用以下方法来查找图像的宽高比:
static string FindAspectRatio(int width, int height)
{
int gcd = FindGcd(width, height);
string ratio = $"{width / gcd}:{height / gcd}";
return ratio;
}
private static int FindGcd(int x, int y)
{
int gcd = 1;
int temp;
if (x > y)
{
temp = x;
x = y;
y = temp;
}
for (int i = 1; i < (x + 1); i++)
{
if (x % i == 0 && y % i == 0)
gcd = i;
}
return gcd;
}
然后,我添加了3个条件检查,用于检查每个图像的Instagram比例。问题是,有时宽高比不是4:5,但高度比Instagram允许的垂直帖子的最大宽高比稍短,这种情况下我不需要应用程序告诉我应该裁剪该图像。是否有任何方法可以实现这一点,以便应用程序可以准确地告诉何时应该裁剪图像?
if (aspectRatio == "4:5" || aspectRatio == "1:1" || aspectRatio == "16:9")
{
continue;
}
请注意,上述代码已经完成了对Instagram的三种常见帖子比例的检查,但如果您希望进行更精确的检查,以确定何时应该裁剪图像,您可能需要添加更多的逻辑来处理边缘情况。这可能需要更复杂的算法和规则。
英文:
I'm trying to make a C# program that gets a directory path and iterate on images, then for each image it should check if that Image it's a fit for instagram post and I don't need to crop it.
Some infos about instagram post ratios:
- Square: 1:1
- Vertical: 4:5
- Horizontal 1.91:1.
I'm using these methods to find image aspect ratio
static string FindAspectRatio(int width, int height)
{
int gcd = FindGcd(width, height);
string ratio = $"{width / gcd}:{height / gcd}";
return ratio;
}
private static int FindGcd(int x, int y)
{
int gcd = 1;
int temp;
if (x > y)
{
temp = x;
x = y;
y = temp;
}
for (int i = 1; i < (x + 1); i++)
{
if (x % i == 0 && y % i == 0)
gcd = i;
}
return gcd;
}
then I added 3 if checks for instagram ratios to check with each image.
The problem is that sometimes the aspect ratio is not 4:5 but the height is a bit shorter than max aspect ratio instagram allows for vertical posts and on that case I don't need the app to tell me that I should crop that image. Is there anyway to achieve this so the app can exactly tell when an image should be cropped?
if (aspectRatio == "4:5" || aspectRatio == "1:1" || aspectRatio == "16:9")
{
continue;
}
答案1
得分: 1
以下是翻译好的代码部分:
static bool InstaRatioValid(decimal ratio)
{
if (ratio >= 0.80M && ratio <= 1.92M)
{
return true;
}
return false;
}
static decimal FindAspectRatio(int width, int height)
{
decimal ratio = Math.Round((decimal)width / height, 2, MidpointRounding.ToZero);
return ratio;
}
希望这对你有帮助!
英文:
Okay I was able to solve it by experimenting with different values,
static bool InstaRatioValid(decimal ratio)
{
if(ratio >= 0.80M && ratio <= 1.92M)
{
return true;
}
return false;
}
static decimal FindAspectRatio(int width, int height)
{
decimal ratio = Math.Round((decimal)width / height, 2,MidpointRounding.ToZero);
return ratio;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论