Aspose.PSD使用教程:使用 Java 裁剪或旋转 PSD 图像

945 阅读2分钟

PSD图像文件用于为徽标、横幅、小册子和许多其他目的设计图片。在某些情况下,可能需要在 Java 应用程序中裁剪或旋转 PSD 文件。本文介绍了如何使用 Java 以编程方式裁剪或旋转 PSD 文件。您需要配置Aspose.PSD for Java API才能使用几种受支持的文件格式。如果你还没有用过Aspose.PSD可以登陆 慧都官网 下载最新版。

使用 Java 使用 Shift 方法裁剪 PSD 图像

您可以根据需要通过移动内容来裁剪 PSD 图像。请按照以下步骤通过移动内容裁剪图像:

  • 将输入 PSD 文件加载到RasterImage类对象中。
  • 使用cacheData方法缓存图像。
  • 定义移位值并将它们传递给crop方法。
  • 保存输出裁剪的图像。

以下代码显示了如何通过使用 Java 以编程方式移动内容来裁剪 PSD 图像:

// Load an existing image into an instance of RasterImage class
RasterImage rasterImage = (RasterImage)Image.load("Test.psd");
     
// Before cropping, the image should be cached for better performance
if (!rasterImage.isCached())
{
    rasterImage.cacheData();
}

// Define shift values for all four sides
int leftShift = 10;
int rightShift = 10;
int topShift = 10;
int bottomShift = 10;

// Based on the shift values, apply the cropping on image.
// Crop method will shift the image bounds toward the center of image and Save the results to disk
rasterImage.crop(leftShift, rightShift, topShift, bottomShift);

// Save output in JPEG,PSD or any other format.
rasterImage.save("output.jpg", new JpegOptions());
rasterImage.save("output.psd", new PsdOptions());

在 Java 中使用矩形坐标裁剪 PSD 图像

您可以通过指定坐标来裁剪 PSD 图像中的任何矩形区域。您需要按照以下步骤裁剪 PSD 图像:

  • 将现有图像加载到RasterImage类的实例中。
  • 缓存图像以获得更好的性能。
  • 创建具有所需大小的Rectangle类实例。
  • 使用裁剪方法裁剪图像并保存输出文件。

下面的代码片段演示了如何使用 Java 裁剪具有直角坐标的 PSD 文件:

String sourceFile = "sample.psd";
String destName = "Cropping-PSD_out.jpg";

// Load an existing image into an instance of RasterImage class
RasterImage rasterImage = (RasterImage)Image.load(sourceFile);
    
// Cache the image for better performance
if (!rasterImage.isCached())
{
   rasterImage.cacheData();
}

// Create an instance of Rectangle class with desired size. 
Rectangle rectangle = new Rectangle(20, 20, 20, 20);

// Perform the crop operation on object of Rectangle class
rasterImage.crop(rectangle);

// Save the results to disk
rasterImage.save(destName, new JpegOptions());

使用 Java 以任意角度旋转 PSD 图像

在某些情况下,您可能需要以特定角度旋转 PSD 图像。请按照以下步骤旋转 PSD 图像:

  • 使用RasterImage类加载源 PSD 图像文件。
  • 在旋转之前,应缓存图像以提高性能。
  • 在旋转方法中指定旋转角度。
  • 保存输出文件。

下面的代码示例解释了如何使用 Java 旋转 PSD 图像:

String sourceFile = "sample.psd";
String destName = "Rotate-PSD_out.jpg";
       
// Load input PSD image file
RasterImage image = (RasterImage)Image.load(sourceFile);

// Before rotation, the image should be cached for better performance
if (!image.isCached())
{
    image.cacheData();
}

// Rotate the PSD image on 20 degree angle while keeping the image size proportional with red background color
image.rotate(20f, true, Color.getRed());

// Save the result to a new file
image.save(destName, new JpegOptions());