【发布时间】:2021-08-09 13:19:02
【问题描述】:
所以我得到了一个用 C# 编写的类及其方法 基本上它的作用是通过 x 和 y 坐标以及高度、宽度截取屏幕的一部分 我想将此 c# 代码转换为 JAVA,以便可以在我的桌面 UI 自动化项目中使用它 所以这是一个基于屏幕“X”和“Y”坐标拍摄图像的实用程序 请注意:我已经尝试过在线转换器,它生成的代码显示库包错误
下面是代码:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace myClass
{
class ImageCapture
{
public static void Capture(string fileName, Point firstCoordinate, Point secondCoordinate, int enlargeImageByPercentage=0)
{
var tmpImg = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).Replace("Roaming", "Local") + "\\temp", Path.GetFileName(fileName));
Rectangle rect = new Rectangle(firstCoordinate.X, firstCoordinate.Y, secondCoordinate.X - firstCoordinate.X, secondCoordinate.Y - firstCoordinate.Y);
Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
bmp.Save(tmpImg, ImageFormat.Jpeg);
g.Dispose();
bmp.Dispose();
if (File.Exists(fileName)) File.Delete(fileName);
if (enlargeImageByPercentage != 0)
{
Image imgToEnlarge = Image.FromFile(tmpImg);
Image resizedImg = resizeImage(tmpImg, new Size(imgToEnlarge.Size.Width * enlargeImageByPercentage, imgToEnlarge.Size.Height * enlargeImageByPercentage));
resizedImg.Save(fileName, ImageFormat.Jpeg);
}
else
{
File.Copy(tmpImg, fileName, true);
}
}
private static Image resizeImage(string imgToResize, Size size)
{
Image _img = Image.FromFile(imgToResize);
//Get the image current width
int sourceWidth = _img.Width;
//Get the image current height
int sourceHeight = _img.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
//Calulate width with new desired size
nPercentW = ((float)size.Width / (float)sourceWidth);
//Calculate height with new desired size
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
//New Width
int destWidth = (int)(sourceWidth * nPercent);
//New Height
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw image with new width and height
g.DrawImage(_img, 0, 0, destWidth, destHeight);
return b;
}
}
}
【问题讨论】:
标签: java image-processing coordinates screen screenshot