Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active March 29, 2024 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save aspose-com-gists/31800d807a72f1f50fe4b29374119227 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/31800d807a72f1f50fe4b29374119227 to your computer and use it in GitHub Desktop.
Gist for Aspose.PSD for Java.
public class AdjustmentLayerEnhancementTest {
public static void main(String[] args) {
String sourcePsd = "AllAdjustments.psd";
String outputOrigPng = "AllAdjustments_orig.png";
String outputModPng = "AllAdjustments_mod.png";
PngOptions pngOpt = new PngOptions();
pngOpt.setColorType(PngColorType.TruecolorWithAlpha);
try (PsdImage image = (PsdImage) PsdImage.load(sourcePsd)) {
image.save(outputOrigPng, pngOpt);
Layer[] layers = image.getLayers();
for (Layer layer : layers) {
if (layer instanceof BrightnessContrastLayer) {
BrightnessContrastLayer br = (BrightnessContrastLayer) layer;
br.setBrightness(-br.getBrightness());
br.setContrast(-br.getContrast());
}
if (layer instanceof LevelsLayer) {
LevelsLayer levels = (LevelsLayer) layer;
LevelChannel masterChannel = levels.getMasterChannel();
masterChannel.setOutputShadowLevel((short) 30);
masterChannel.setInputShadowLevel((short) 5);
masterChannel.setInputMidtoneLevel(2);
masterChannel.setOutputHighlightLevel((short) 213);
masterChannel.setInputHighlightLevel((short) 120);
}
if (layer instanceof CurvesLayer) {
CurvesLayer curves = (CurvesLayer) layer;
CurvesContinuousManager manager = (CurvesContinuousManager) curves.getCurvesManager();
manager.addCurvePoint(2, (byte) 150, (byte) 180);
}
if (layer instanceof ExposureLayer) {
ExposureLayer exp = (ExposureLayer) layer;
exp.setExposure((float) (exp.getExposure() + 0.1));
}
if (layer instanceof HueSaturationLayer) {
HueSaturationLayer hue = (HueSaturationLayer) layer;
hue.setHue((short) -15);
hue.setSaturation((short) 30);
}
if (layer instanceof ColorBalanceAdjustmentLayer) {
ColorBalanceAdjustmentLayer colorBal = (ColorBalanceAdjustmentLayer) layer;
colorBal.setMidtonesCyanRedBalance((short) 30);
}
if (layer instanceof BlackWhiteAdjustmentLayer) {
BlackWhiteAdjustmentLayer bw = (BlackWhiteAdjustmentLayer) layer;
bw.setReds(30);
bw.setGreens(25);
bw.setBlues(40);
}
if (layer instanceof PhotoFilterLayer) {
PhotoFilterLayer photoFilter = (PhotoFilterLayer) layer;
photoFilter.setColor(Color.getAzure());
}
if (layer instanceof ChannelMixerLayer) {
ChannelMixerLayer channelMixer = (ChannelMixerLayer) layer;
RgbMixerChannel channel = (RgbMixerChannel) channelMixer.getChannelByIndex(0);
channel.setGreen((short) 120);
channel.setRed((short) 50);
channel.setBlue((short) 70);
channel.setConstant((short) (channel.getConstant() + 10));
}
if (layer instanceof PosterizeLayer) {
PosterizeLayer post = (PosterizeLayer) layer;
post.setLevels((short) 3);
}
if (layer instanceof ThresholdLayer) {
ThresholdLayer threshold = (ThresholdLayer) layer;
threshold.setLevel((short) 15);
}
if (layer instanceof SelectiveColorLayer) {
SelectiveColorLayer selectiveColor = (SelectiveColorLayer) layer;
CmykCorrection correction = new CmykCorrection();
correction.setCyan((short) 25);
correction.setMagenta((short) 10);
correction.setYellow((short) -15);
correction.setBlack((short) 5);
selectiveColor.setCmykCorrection(SelectiveColorsTypes.Cyans, correction);
}
}
image.save(outputModPng, pngOpt);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class AddFileAsLayer {
public static void main(String[] args) {
String inputFile = "inputFile.png";
String outputFile = "AddFileAsLayer.psd";
try {
// Read input file as bytes
byte[] fileBytes = readBytesFromFile(inputFile);
// Create PSD Layer from byte array
ByteArrayInputStream stream = new ByteArrayInputStream(fileBytes);
try (Layer layer = new Layer(stream);
// Create PSD Image with the specified size
PsdImage psdImage = new PsdImage(layer.getWidth(), layer.getHeight())) {
// Add Layer to PSD Image
psdImage.setLayers(new Layer[]{layer});
// Get Pixels from File
int[] pixels = layer.loadArgb32Pixels(layer.getBounds());
int pixelsLength = pixels.length;
// Fill the pixels data with some values
for (int i = 0; i < pixelsLength; i++) {
if (i % 5 == 0) {
pixels[i] = 500000;
}
}
// Fast Save of Updated Image Data
layer.saveArgb32Pixels(layer.getBounds(), pixels);
// Save PSD Image
psdImage.save(outputFile);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static byte[] readBytesFromFile(String filePath) throws IOException {
FileInputStream fileInputStream = new FileInputStream(filePath);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
fileInputStream.close();
outputStream.close();
return outputStream.toByteArray();
}
}
public class AddFileAsLayer {
public static void main(String[] args) {
String inputFile = "inputFile.png";
String outputFile = "AddFileAsLayer.psd";
try {
// Open file as InputStream
try (InputStream inputStream = Files.newInputStream(Paths.get(inputFile))) {
// Create PSD Layer from InputStream
Layer layer = new Layer(inputStream);
// Create PSD Image with the specified size
try (PsdImage psdImage = new PsdImage(layer.getWidth(), layer.getHeight())) {
// Add Layer to PSD Image
psdImage.setLayers(new Layer[]{layer});
// Get Pixels from File
int[] pixels = layer.loadArgb32Pixels(layer.getBounds());
int pixelsLength = pixels.length;
// Fill the pixels data with some values
for (int i = 0; i < pixelsLength; i++) {
if (i % 5 == 0) {
pixels[i] = 500000;
}
}
// Fast Save of Updated Image Data
layer.saveArgb32Pixels(layer.getBounds(), pixels);
// Save PSD Image
try (OutputStream outputStream = Files.newOutputStream(Paths.get(outputFile))) {
psdImage.save(outputStream);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
String source = "AllTypesLayerPsd2.psd";
String outputOriginal = "original.png";
String outputUpdated = "output_updated.png";
try (PsdImage image = (PsdImage) Image.load(source)) {
PngOptions pngSaveOpt = new PngOptions();
pngSaveOpt.setColorType(PngColorType.TruecolorWithAlpha);
image.save(outputOriginal, pngSaveOpt);
// Change opacity and/or blending mode of layer
image.getLayers()[1].setOpacity((byte) 100);
image.getLayers()[4].setBlendModeKey(BlendMode.Hue);
// Add effects like shadow and color overlay and set it up
DropShadowEffect shadow = image.getLayers()[7].getBlendingOptions().addDropShadow();
shadow.setAngle(30);
shadow.setColor(Color.fromArgb(255, 255, 0));
image.getLayers()[9].setBlendModeKey(BlendMode.Lighten);
ColorOverlayEffect colorOverlay = image.getLayers()[5].getBlendingOptions().addColorOverlay();
colorOverlay.setColor(Color.fromArgb(200, 30, 50));
colorOverlay.setOpacity((byte) 150);
image.save(outputUpdated, pngSaveOpt);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void convertAItoJPEG() {
String sourceFile = "raster.ai";
String outputFile = "raster_output.jpg";
// Initialize JpegOptions and set quality
JpegOptions jpegOptions = new JpegOptions();
jpegOptions.setQuality(95);
// Load AI image and save as JPEG
try (Image image = Image.load(sourceFile)) {
image.save(outputFile, jpegOptions);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
convertAItoJPEG();
}
public static void convertAIToPDF() {
String sourceFile = "raster.ai";
String outputFile = "output.pdf";
try (Image image = Image.load(sourceFile)) {
image.save(outputFile, new PdfOptions());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
convertAIToPDF();
}
public class ConvertAIToPNG {
public static void main(String[] args) {
String sourceFile = "raster.ai";
String outputFile = "raster_output.png";
// Load AI image
try (AiImage image = (AiImage) Image.load(sourceFile)) {
// Convert and save to PNG
image.save(outputFile, new PngOptions());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
convertBetweenColorModesAndBitDepthTest();
}
public static void convertBetweenColorModesAndBitDepthTest() {
String sourceFileName = "John-OConnor_Spring-Reflections_example.psd";
String outputFileName = "result.psd";
try (PsdImage image = (PsdImage) PsdImage.load(sourceFileName)) {
PsdOptions psdSaveOpt = new PsdOptions();
psdSaveOpt.setChannelsCount((short) 5);
psdSaveOpt.setColorMode(ColorModes.Cmyk);
psdSaveOpt.setCompressionMethod(CompressionMethod.RLE);
image.save(outputFileName, psdSaveOpt);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class CreateFileFromScratchExample {
public static void main(String[] args) {
String outputFile = "CreateFileFromScratchExample.psd";
// Create PSD Image with specified dimensions
try (PsdImage img = new PsdImage(500, 500)) {
// Create Regular PSD Layer and update it with Graphic API
Layer regularLayer = img.addRegularLayer();
// Use popular Graphic API for Editing
Graphics graphics = new Graphics(regularLayer);
Pen pen = new Pen(Color.getAliceBlue());
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(250, 250, 150, 100),
Color.getRed(), Color.getAquamarine(), 45);
graphics.drawEllipse(pen, new Rectangle(100, 100, 200, 200));
graphics.fillEllipse(brush, new Rectangle(250, 250, 150, 100));
// Create Text Layer
TextLayer textLayer = img.addTextLayer("Sample Text", new Rectangle(200, 200, 100, 100));
// Adding Shadow to Text
DropShadowEffect dropShadowEffect = textLayer.getBlendingOptions().addDropShadow();
dropShadowEffect.setDistance(0);
dropShadowEffect.setSize(8);
dropShadowEffect.setColor(Color.getBlue());
// Save PSD File
img.save(outputFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class LayerManipulation {
public static Layer createRegularLayer(int left, int top, int width, int height) {
Layer layer = new Layer();
layer.setLeft(left);
layer.setTop(top);
layer.setRight(left + width);
layer.setBottom(top + height);
int color = Color.getAqua().toArgb();
int[] testData = new int[width * height];
for (int i = 0; i < width * height; i++) {
testData[i] = color;
}
layer.saveArgb32Pixels(layer.getBounds(), testData);
return layer;
}
public static void fillLayerManipulationTest() {
String outputPng = "all_fill_layers.png";
String outputPsd = "all_fill_layers.psd";
try (PsdImage image = new PsdImage(100, 100)) {
Layer layer1 = createRegularLayer(0, 0, 50, 50);
image.addLayer(layer1);
FillLayer colorFillLayer = FillLayer.createInstance(FillType.Color);
ColorFillSettings colorFillSettings = (ColorFillSettings) colorFillLayer.getFillSettings();
colorFillSettings.setColor(Color.getCoral());
colorFillLayer.setClipping((byte) 1);
colorFillLayer.setDisplayName("Color Fill Layer");
image.addLayer(colorFillLayer);
Layer layer2 = createRegularLayer(50, 0, 50, 50);
image.addLayer(layer2);
GradientColorPoint[] gradientColorPoints = new GradientColorPoint[]{
new GradientColorPoint(Color.getRed(), 2048, 50),
new GradientColorPoint(Color.getGreen(), 3072, 50),
new GradientColorPoint(Color.getBlue(), 4096, 50)};
GradientTransparencyPoint tp1 = new GradientTransparencyPoint();
tp1.setLocation(0);
tp1.setMedianPointLocation(50);
tp1.setOpacity(128);
GradientTransparencyPoint tp2 = new GradientTransparencyPoint();
tp2.setLocation(2048);
tp2.setMedianPointLocation(50);
tp2.setOpacity(176);
GradientTransparencyPoint[] gradientTransparencyPoints = new GradientTransparencyPoint[]{tp1, tp2};
FillLayer gradientFillLayer = FillLayer.createInstance(FillType.Gradient);
gradientFillLayer.setDisplayName("Gradient Fill Layer");
GradientFillSettings gradientFillSettings = (GradientFillSettings) gradientFillLayer.getFillSettings();
gradientFillSettings.setColorPoints(gradientColorPoints);
gradientFillSettings.setAngle(-45);
gradientFillSettings.setTransparencyPoints(gradientTransparencyPoints);
gradientFillLayer.setClipping((byte) 1);
image.addLayer(gradientFillLayer);
Layer layer3 = createRegularLayer(0, 50, 50, 50);
image.addLayer(layer3);
FillLayer patternFillLayer = FillLayer.createInstance(FillType.Pattern);
patternFillLayer.setDisplayName("Pattern Fill Layer");
patternFillLayer.setOpacity((byte) 50);
patternFillLayer.setClipping((byte) 1);
PatternFillSettings patternFillSettings = (PatternFillSettings) patternFillLayer.getFillSettings();
patternFillSettings.setPatternData(new int[]{
Color.getRed().toArgb(), Color.getTransparent().toArgb(), Color.getTransparent().toArgb(),
Color.getTransparent().toArgb(), Color.getRed().toArgb(), Color.getTransparent().toArgb(),
Color.getTransparent().toArgb(), Color.getTransparent().toArgb(), Color.getRed().toArgb()
});
patternFillSettings.setPatternWidth(3);
patternFillSettings.setPatternHeight(3);
image.addLayer(patternFillLayer);
PngOptions pngOpt = new PngOptions();
pngOpt.setColorType(PngColorType.TruecolorWithAlpha);
image.save(outputPng, pngOpt);
image.save(outputPsd);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
fillLayerManipulationTest();
}
}
public static void main(String[] args) {
try {
PsdLoadOptions loadOpt = new PsdLoadOptions();
loadOpt.setLoadEffectsResource(true);
loadOpt.setAllowWarpRepaint(true);
String inputFile = "AllTypesLayerPsd.psd";
String psdName = "using_graphics_output.psd";
String pngName = "using_graphics_output.png";
try (PsdImage psdImage = (PsdImage) Image.load((inputFile), loadOpt)) {
// You can use Graphics API for editing layers
Graphics graphics = new Graphics(psdImage.getLayers()[0]);
Pen pen = new Pen(Color.getAliceBlue());
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(250, 250, 150, 100), Color.getRed(), Color.getGreen(), 45);
graphics.drawEllipse(pen, new Rectangle(100, 100, 200, 200));
graphics.fillEllipse(brush, new Rectangle(250, 250, 150, 100));
psdImage.save(psdName);
psdImage.save(pngName, new PngOptions());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class LayerGroupManipulationTest {
public static void main(String[] args) {
String outputPsd = "LayerGroup.psd";
try (FileInputStream fileInputStream = new FileInputStream(outputPsd)) {
PsdOptions psdOptions = new PsdOptions();
psdOptions.setSource(new StreamSource(fileInputStream));
try (PsdImage image = (PsdImage) Image.create(psdOptions, 100, 100)) {
LayerGroup layerGroup = image.addLayerGroup("Folder", 0, true);
Layer layer1 = new Layer();
layer1.setDisplayName("Layer 1");
Layer layer2 = new Layer();
layer2.setDisplayName("Layer 2");
layerGroup.addLayer(layer1);
layerGroup.addLayer(layer2);
assert layerGroup.getLayers()[0].getDisplayName().equals("Layer 1");
assert layerGroup.getLayers()[1].getDisplayName().equals("Layer 2");
image.save(outputPsd);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void layerEffectsFullTest() {
String source = "/ShowCases/nines.psd";
String resultOrig = "nines_orig.png";
String resultPsd = "nines_mod.psd";
String resultMod = "nines_mod.png";
// Set the PNG options
PngOptions pngOpt = new PngOptions();
pngOpt.setColorType(PngColorType.TruecolorWithAlpha);
// Set the PSD load options
PsdLoadOptions psdLoadOptions = new PsdLoadOptions();
psdLoadOptions.setLoadEffectsResource(true);
// Load the PSD image
try (PsdImage image = (PsdImage) Image.load(source, psdLoadOptions)) {
// Save the original image as PNG
image.save(resultOrig, pngOpt);
// Test data for gradient
GradientColorPoint[] gradientColorPoints = new GradientColorPoint[]{
new GradientColorPoint(Color.getRed(), 0, 50),
new GradientColorPoint(Color.getGreen(), 1024, 50),
new GradientColorPoint(Color.getBlue(), 2048, 50)
};
GradientTransparencyPoint tp1 = new GradientTransparencyPoint();
tp1.setLocation(0);
tp1.setMedianPointLocation(50);
tp1.setOpacity(128);
GradientTransparencyPoint tp2 = new GradientTransparencyPoint();
tp2.setLocation(2048);
tp2.setMedianPointLocation(50);
tp2.setOpacity(176);
GradientTransparencyPoint[] gradientTransparencyPoints = new GradientTransparencyPoint[]{tp1, tp2};
// Add stroke to layer 1
StrokeEffect stroke = image.getLayers()[1].getBlendingOptions().addStroke(FillType.Gradient);
stroke.setSize(3);
GradientFillSettings gradientFillSettings = (GradientFillSettings) stroke.getFillSettings();
gradientFillSettings.setColorPoints(gradientColorPoints);
gradientFillSettings.setTransparencyPoints(gradientTransparencyPoints);
// Add inner shadow to layer 2
InnerShadowEffect innerShadow = image.getLayers()[2].getBlendingOptions().addInnerShadow();
innerShadow.setAngle(60);
innerShadow.setColor(Color.getYellow());
// Add drop shadow to layer 3
DropShadowEffect dropShadow = image.getLayers()[3].getBlendingOptions().addDropShadow();
dropShadow.setAngle(30);
dropShadow.setColor(Color.getViolet());
// Add gradient overlay to layer 4
GradientOverlayEffect gradientOverlay = image.getLayers()[4].getBlendingOptions().addGradientOverlay();
gradientOverlay.getSettings().setColorPoints(gradientColorPoints);
gradientOverlay.getSettings().setTransparencyPoints(gradientTransparencyPoints);
// Add color overlay to layer 5
ColorOverlayEffect colorOverlay = image.getLayers()[5].getBlendingOptions().addColorOverlay();
colorOverlay.setColor(Color.getAzure());
colorOverlay.setOpacity((byte) 120);
// Add pattern overlay to layer 6
PatternOverlayEffect patternOverlay = image.getLayers()[6].getBlendingOptions().addPatternOverlay();
int[] patternData = new int[]{
Color.getRed().toArgb(), Color.getTransparent().toArgb(),
Color.getTransparent().toArgb(), Color.getRed().toArgb()
};
patternOverlay.getSettings().setPatternData(patternData);
patternOverlay.getSettings().setPatternWidth(2);
patternOverlay.getSettings().setPatternHeight(2);
// Add outer glow to layer 7
OuterGlowEffect outerGlow = image.getLayers()[7].getBlendingOptions().addOuterGlow();
outerGlow.setSize(10);
ColorFillSettings colorFillSettings = new ColorFillSettings();
colorFillSettings.setColor(Color.getCrimson());
outerGlow.setFillColor(colorFillSettings);
// Save the modified image as PNG and PSD
image.save(resultMod, pngOpt);
image.save(resultPsd);
}
}
public class LayerManipulationTest {
public static void main(String[] args) {
String source = "AllTypesLayerPsd2.psd";
String outputOriginal = "original_layer_manipulation.png";
String outputUpdated = "updated_layer_manipulation.png";
PngOptions pngOpt = new PngOptions();
pngOpt.setColorType(PngColorType.TruecolorWithAlpha);
try (PsdImage psdImage = (PsdImage) Image.load(source)) {
psdImage.save(outputOriginal, pngOpt);
// Resizing
psdImage.getLayers()[2].resize(25, 25, ResizeType.HighQualityResample);
// Rotating
psdImage.getLayers()[5].rotate(45, true, Color.getYellow());
// Simple Filters
psdImage.getLayers()[3].adjustContrast(3);
// Cropping
psdImage.getLayers()[10].crop(new Rectangle(10, 10, 20, 20));
psdImage.save(outputUpdated, pngOpt);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void exportPsdAndAIToDifferentFormatsTest() {
// Saving to PNG
PngOptions pngSaveOpt = new PngOptions();
pngSaveOpt.setColorType(PngColorType.TruecolorWithAlpha);
// Saving to PDF
PdfOptions pdfSaveOpt = new PdfOptions();
// Saving to Tiff
TiffOptions tiffSaveOpt = new TiffOptions(TiffExpectedFormat.TiffNoCompressionRgba);
// Saving to Jpeg
JpegOptions jpegSaveOpt = new JpegOptions();
jpegSaveOpt.setQuality(90);
// Saving to BMP
BmpOptions bmpSaveOpt = new BmpOptions();
// Saving to JPEG2000
Jpeg2000Options j2kSaveOpt = new Jpeg2000Options();
// Saving to GIF
GifOptions gifSaveOpt = new GifOptions();
// Saving to PSB
PsdOptions psbSaveOpt = new PsdOptions();
psbSaveOpt.setVersion(2);
// Saving to PSD
PsdOptions psdSaveOpt = new PsdOptions();
Map<String, ImageOptionsBase> formats = new HashMap<>();
formats.put("pdf", pdfSaveOpt);
formats.put("jpg", jpegSaveOpt);
formats.put("png", pngSaveOpt);
formats.put("tif", tiffSaveOpt);
formats.put("gif", gifSaveOpt);
formats.put("j2k", j2kSaveOpt);
formats.put("bmp", bmpSaveOpt);
formats.put("psb", psbSaveOpt);
formats.put("psd", psdSaveOpt);
// Saving PSD to other formats
String sourcePsd = "AllTypesLayerPsd2.psd";
try (PsdImage image = (PsdImage) com.aspose.psd.Image.load(sourcePsd)) {
for (Map.Entry<String, ImageOptionsBase> entry : formats.entrySet()) {
String format = entry.getKey();
ImageOptionsBase saveOpt = entry.getValue();
String fn = "export.psd.to." + format;
image.save(fn, saveOpt);
}
}
// Saving AI to other formats
String sourceAi = "ai_one_text_3.ai";
try (AiImage image = (AiImage) com.aspose.psd.Image.load(sourceAi)) {
for (Map.Entry<String, ImageOptionsBase> entry : formats.entrySet()) {
String format = entry.getKey();
ImageOptionsBase saveOpt = entry.getValue();
String fn = "export.ai.to." + format;
image.save(fn, saveOpt);
}
}
}
public class ShapeLayerPathManipulationTest {
public static void main(String[] args) {
String sourceFileName = "ShapeLayerTest.psd";
String originalOutput = "ShapeLayerTest_Res_or.psd";
String updatedOutput = "ShapeLayerTest_Res_up.psd";
try (PsdImage image = (PsdImage) Image.load(sourceFileName)) {
image.save(originalOutput);
for (Layer layer : image.getLayers()) {
// Finding Shape Layer
if (layer instanceof ShapeLayer) {
ShapeLayer shapeLayer = (ShapeLayer) layer;
IPath path = shapeLayer.getPath();
IPathShape[] pathShapes = path.getItems();
List<BezierKnotRecord[]> knotsList = new ArrayList<>();
for (IPathShape pathShape : pathShapes) {
knotsList.add(pathShape.getItems());
}
// Change Path Shape properties
PathShape newShape = new PathShape();
BezierKnotRecord bn1 = new BezierKnotRecord();
bn1.setLinked(true);
bn1.setPoints(new Point[]{
PointFToResourcePoint(new PointF(20, 100), Size.to_SizeF(shapeLayer.getContainer().getSize())),
PointFToResourcePoint(new PointF(20, 100), Size.to_SizeF(shapeLayer.getContainer().getSize())),
PointFToResourcePoint(new PointF(20, 100), Size.to_SizeF(shapeLayer.getContainer().getSize()))
});
BezierKnotRecord bn2 = new BezierKnotRecord();
bn2.setLinked(true);
bn2.setPoints(new Point[]{
PointFToResourcePoint(new PointF(20, 490), Size.to_SizeF(shapeLayer.getContainer().getSize())),
PointFToResourcePoint(new PointF(20, 490), Size.to_SizeF(shapeLayer.getContainer().getSize())),
PointFToResourcePoint(new PointF(20, 490), Size.to_SizeF(shapeLayer.getContainer().getSize()))
});
BezierKnotRecord bn3 = new BezierKnotRecord();
bn3.setLinked(true);
bn3.setPoints(new Point[]{
PointFToResourcePoint(new PointF(490, 20), Size.to_SizeF(shapeLayer.getContainer().getSize())),
PointFToResourcePoint(new PointF(490, 20), Size.to_SizeF(shapeLayer.getContainer().getSize())),
PointFToResourcePoint(new PointF(490, 20), Size.to_SizeF(shapeLayer.getContainer().getSize()))
});
BezierKnotRecord[] bezierKnots = {bn1, bn2, bn3};
newShape.setItems(bezierKnots);
List<IPathShape> newShapes = Arrays.asList(pathShapes);
newShapes.add(newShape);
path.setItems(newShapes.toArray(new IPathShape[0]));
shapeLayer.update();
image.save(updatedOutput);
break;
}
}
}
}
private static Point PointFToResourcePoint(PointF point, SizeF imageSize) {
double ImgToPsdRatio = 256 * 65535;
return new Point((int) (point.getY() * (ImgToPsdRatio / imageSize.getHeight())), (int) (point.getX() * (ImgToPsdRatio / imageSize.getWidth())));
}
}
public class SmartFilterDirectApply {
public static void main(String[] args) {
String source = "VerySmoothPicture.psd";
String outputOriginal = "original_smart.psd";
String outputUpdated = "output_updated.psd";
try (PsdImage psdImage = (PsdImage) Image.load(source)) {
psdImage.save(outputOriginal);
SharpenSmartFilter sharpenFilter = new SharpenSmartFilter();
for (int i = 0; i < 3; i++) {
sharpenFilter.apply(psdImage.getLayers()[1]);
}
psdImage.save(outputUpdated);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class SmartFilterFeaturesTest {
public static void main(String[] args) {
String source = "r2_SmartFilters.psd";
String outputOriginal = "original_smart_features.psd";
String outputUpdated = "output_updated_features.psd";
try (PsdImage psdImage = (PsdImage) Image.load(source)) {
psdImage.save(outputOriginal);
SmartObjectLayer smartObj = (SmartObjectLayer) psdImage.getLayers()[1];
// Edit Gaussian Blur Smart Filter
GaussianBlurSmartFilter gaussianBlur = (GaussianBlurSmartFilter) smartObj.getSmartFilters().getFilters()[0];
gaussianBlur.setRadius(1);
gaussianBlur.setBlendMode(BlendMode.Divide);
gaussianBlur.setOpacity(75);
gaussianBlur.setEnabled(false);
// Edit Add Noise Smart Filter
AddNoiseSmartFilter addNoise = (AddNoiseSmartFilter) smartObj.getSmartFilters().getFilters()[1];
addNoise.setDistribution(NoiseDistribution.Uniform);
// Add new filter items
SmartFilter[] filters = smartObj.getSmartFilters().getFilters();
filters[smartObj.getSmartFilters().getFilters().length] = new GaussianBlurSmartFilter();
filters[smartObj.getSmartFilters().getFilters().length] = new AddNoiseSmartFilter();
smartObj.getSmartFilters().setFilters(filters);
// Apply changes
smartObj.getSmartFilters().updateResourceValues();
// Apply filters directly to layer and mask of layer
smartObj.getSmartFilters().getFilters()[0].apply(psdImage.getLayers()[2]);
smartObj.getSmartFilters().getFilters()[4].applyToMask(psdImage.getLayers()[2]);
psdImage.save(outputUpdated);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
smartObjectManipulationTest();
}
// Just inverts all data of image
private static void invertImage(PsdImage image) {
int[] pixels = image.loadArgb32Pixels(image.getBounds());
for (int i = 0; i < pixels.length; i++) {
int pixel = pixels[i];
int alpha = pixel & 0xff000000;
pixels[i] = (~(pixel & 0x00ffffff)) | alpha;
}
image.saveArgb32Pixels(image.getBounds(), pixels);
}
// Demonstration of API to work with Smart Object Layers
private static void smartObjectManipulationTest() {
String source = "new_panama-papers-8-trans4.psd";
String exportContentPath = "export_content.jpg";
String outputOriginal = "smart_object_orig.psd";
String outputUpdated = "smart_object.psd";
try (PsdImage image = (PsdImage) Image.load(source)) {
image.save(outputOriginal);
SmartObjectLayer smartLayer = (SmartObjectLayer) image.getLayers()[0];
// How to export content of Smart Object
smartLayer.exportContents(exportContentPath);
// Creating Smart Object as a Copy
SmartObjectLayer newLayer = smartLayer.newSmartObjectViaCopy();
newLayer.setVisible(false);
newLayer.setDisplayName("Duplicate");
// Get the content of Smart Object for manipulation
try (PsdImage innerImage = (PsdImage) smartLayer.loadContents(null)) {
invertImage(innerImage);
smartLayer.replaceContents(innerImage);
}
image.getSmartObjectProvider().updateAllModifiedContent();
PsdOptions psdOptions = new PsdOptions();
image.save(outputUpdated, psdOptions);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class TextLayerUpdatingTest {
public static void main(String[] args) {
String sourceFile = "text212.psd";
String outputFile = "Output_text212.psd";
try (PsdImage img = (PsdImage) PsdImage.load(sourceFile)) {
// Simple way to update text layer
TextLayer simpleText = (TextLayer) img.getLayers()[2];
simpleText.updateText("Update", Color.getRed());
// More powerful way to update text layer - using Text Portions with different styles and paragraphs
TextLayer textLayer = (TextLayer) img.getLayers()[1];
IText textData = textLayer.getTextData();
ITextStyle defaultStyle = textData.producePortion().getStyle();
ITextParagraph defaultParagraph = textData.producePortion().getParagraph();
defaultStyle.setFillColor(Color.fromName("DimGray"));
defaultStyle.setFontSize(51);
textData.getItems()[1].getStyle().setStrikethrough(true);
// Update text styles for different portions
ITextPortion[] newPortions = textData.producePortions(new String[]{
"E=mc",
"2\r",
"Bold",
"Italic\r",
"Lowercasetext"},
defaultStyle,
defaultParagraph
);
newPortions[0].getStyle().setUnderline(true); // Edit text style "E=mc"
newPortions[1].getStyle().setFontBaseline(FontBaseline.Superscript); // Edit text style "2\r"
newPortions[2].getStyle().setFauxBold(true); // Edit text style "Bold"
newPortions[3].getStyle().setFauxItalic(true); // Edit text style "Italic\r"
newPortions[3].getStyle().setBaselineShift(-25); // Edit text style "Italic\r"
newPortions[4].getStyle().setFontCaps(FontCaps.SmallCaps); // Edit text style "Lowercasetext"
for (ITextPortion newPortion : newPortions) {
textData.addPortion(newPortion);
}
textData.updateLayerData();
img.save(outputFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
String sourceFile = "text212.psd";
String outputFile = "Output_text212.psd";
try (PsdImage image = (PsdImage) PsdImage.load(sourceFile)) {
TextLayer simpleText = (TextLayer) image.getLayers()[2];
simpleText.updateText("Update", Color.getRed());
image.save(outputFile);
}
}
}
public class Main {
public static void main(String[] args) {
String sourceFile = "text212.psd";
try (PsdImage image = (PsdImage) PsdImage.load(sourceFile)) {
// Assuming the necessary imports and classes are available
TextLayer textLayer = (TextLayer) image.getLayers()[1];
IText textData = textLayer.getTextData();
ITextStyle defaultStyle = textData.producePortion().getStyle();
ITextParagraph defaultParagraph = textData.producePortion().getParagraph();
defaultStyle.setFillColor(Color.fromName("DimGray"));
defaultStyle.setFontSize(51);
textData.getItems()[1].getStyle().setStrikethrough(true);
String[] strings = new String[]{"E=mc", "2\r", "Bold", "Italic\r", "Lowercasetext"};
ITextPortion[] newPortions = textData.producePortions(
strings,
defaultStyle,
defaultParagraph
);
newPortions[0].getStyle().setUnderline(true);
newPortions[1].getStyle().setFontBaseline(FontBaseline.Superscript);
newPortions[2].getStyle().setFauxBold(true);
newPortions[3].getStyle().setFauxItalic(true);
newPortions[3].getStyle().setBaselineShift(-25);
newPortions[4].getStyle().setFontCaps(FontCaps.SmallCaps);
for (ITextPortion newPortion : newPortions) {
textData.addPortion(newPortion);
}
textData.updateLayerData();
}
}
}
public class LayerMasksEditingTest {
public static void main(String[] args) {
String source = "MaskExample.psd";
String outputOriginal = "original_mask_features.psd";
String outputUpdated = "updated_mask_features.psd";
try (PsdImage image = (PsdImage) Image.load(source)) {
image.save(outputOriginal);
// Setting Clipping Masks
image.getLayers()[4].setClipping((byte) 1);
image.getLayers()[5].setClipping((byte) 1);
// Adding Mask to Layer
LayerMaskDataShort mask = new LayerMaskDataShort();
mask.setLeft(50);
mask.setTop(213);
mask.setRight(mask.getLeft() + 150);
mask.setBottom(mask.getTop() + 150);
byte[] maskData = new byte[(mask.getRight() - mask.getLeft()) * (mask.getBottom() - mask.getTop())];
for (int index = 0; index < maskData.length; index++) {
maskData[index] = (byte) (100 + index % 100);
}
mask.setImageData(maskData);
image.getLayers()[2].addLayerMask(mask);
image.save(outputUpdated);
}
}
}
Layer bgImageLayer = new Layer(new FileInputStream(bgImagePath));
psdImage.addLayer(bgImageLayer);
Layer graphicLayer = psdImage.addRegularLayer();
Graphics graphics = new Graphics(graphicLayer);
Font georgiaFont = new Font("Georgia Pro Semibold", 105, FontStyle.Regular, GraphicsUnit.Pixel);
int linesCount = text.split(System.getProperty("line.separator")).length;
int textHeight = (int)(georgiaFont.getSize() * 1.15 * linesCount + 3);
graphics.drawString(text, georgiaFont, new SolidBrush(Color.getWhite()),
110, psdImage.getHeight() - 40 - 15 - textHeight);
Rectangle rectangle = new Rectangle(60,
psdImage.getHeight() - 40 - 25 - textHeight - 15, 40, 25 + textHeight + 15);
LinearGradientBrush linearGradientBrush = new LinearGradientBrush(
new Point(rectangle.getLeft(), rectangle.getTop()),
new Point(rectangle.getLeft(), rectangle.getBottom()),
Color.fromArgb(0, 106, 176), Color.fromArgb(0, 152, 255));
graphics.fillRectangle(linearGradientBrush, rectangle);
psdImage.save(outThumbnailPath, new PngOptions());
bgImageLayer.resize(psdImage.getWidth(), psdImage.getHeight());
bgImageLayer.setTop(0);
bgImageLayer.setRight(psdImage.getWidth());
bgImageLayer.setBottom(psdImage.getHeight());
bgImageLayer.setLeft(0);
GradientFillSettings gradientFillSettings = new GradientFillSettings();
gradientFillSettings.setGradientType(GradientType.Radial);
gradientFillSettings.setScale(150);
gradientFillSettings.setTransparencyPoints(new IGradientTransparencyPoint[]{
new GradientTransparencyPoint(0, 3072, 50),
new GradientTransparencyPoint(85, 0, 65),
});
gradientFillSettings.setColorPoints(new IGradientColorPoint[]{
new GradientColorPoint(Color.fromArgb(0, 15, 30), 0, 50),
});
gradientFillSettings.setReverse(true);
gradientFillSettings.setHorizontalOffset(psdImage.getWidth() / 10d);
gradientFillSettings.setVerticalOffset(psdImage.getHeight() / -1.5);
FillLayer gradientLayer = FillLayer.createInstance(FillType.Gradient);
gradientLayer.setFillSettings(gradientFillSettings);
psdImage.addLayer(gradientLayer);
Layer logoLayer = new Layer(new FileInputStream(logoPath));
psdImage.addLayer(logoLayer);
final int logoShift = 60;
logoLayer.setTop(logoLayer.getTop() + logoShift);
logoLayer.setRight(logoLayer.getRight() + logoShift);
logoLayer.setBottom(logoLayer.getBottom() + logoShift);
logoLayer.setLeft(logoLayer.getLeft() + logoShift);
DropShadowEffect dropShadowEffect = logoLayer.getBlendingOptions().addDropShadow();
dropShadowEffect.setDistance(0);
dropShadowEffect.setSize(10);
dropShadowEffect.setOpacity((byte)50);
public static void main(String[] args) throws IOException, java.awt.FontFormatException
{
String text = "Printing out\r\nthe world";
String bgImagePath = "background_image.png";
final String logoPath = "DW-Logo-white.png";
final String outThumbnailPath = "thumbnail.png";
final String georgiaFontPath = "GeorgiaPro-SemiBold.ttf";
// Register a custom font
java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment()
.registerFont(java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT,
new File(georgiaFontPath)));
// Create a new Photoshop document with Full HD 1080p resolution
PsdImage psdImage = new PsdImage(1280, 720);
try
{
// Load a background image as a layer and bind one to the document
Layer bgImageLayer = new Layer(new FileInputStream(bgImagePath));
psdImage.addLayer(bgImageLayer);
// Fit the background image size to the document size
bgImageLayer.resize(psdImage.getWidth(), psdImage.getHeight());
// Reset the position of the layer (bind to upper left corner)
bgImageLayer.setTop(0);
bgImageLayer.setRight(psdImage.getWidth());
bgImageLayer.setBottom(psdImage.getHeight());
bgImageLayer.setLeft(0);
// Configure the radial gradient
GradientFillSettings gradientFillSettings = new GradientFillSettings();
gradientFillSettings.setGradientType(GradientType.Radial);
gradientFillSettings.setScale(150);
gradientFillSettings.setTransparencyPoints(new IGradientTransparencyPoint[]{
new GradientTransparencyPoint(0, 3072, 50),
new GradientTransparencyPoint(85, 0, 65),
});
gradientFillSettings.setColorPoints(new IGradientColorPoint[]{
new GradientColorPoint(Color.fromArgb(0, 15, 30), 0, 50),
});
gradientFillSettings.setReverse(true);
gradientFillSettings.setHorizontalOffset(psdImage.getWidth() / 10d);
gradientFillSettings.setVerticalOffset(psdImage.getHeight() / -1.5);
// Bind the gradient fill layer to the document
FillLayer gradientLayer = FillLayer.createInstance(FillType.Gradient);
gradientLayer.setFillSettings(gradientFillSettings);
psdImage.addLayer(gradientLayer);
// Add a logo as a layer and bind one to the document
Layer logoLayer = new Layer(new FileInputStream(logoPath));
psdImage.addLayer(logoLayer);
// Move the logo 60px away from upper left corner
final int logoShift = 60;
logoLayer.setTop(logoLayer.getTop() + logoShift);
logoLayer.setRight(logoLayer.getRight() + logoShift);
logoLayer.setBottom(logoLayer.getBottom() + logoShift);
logoLayer.setLeft(logoLayer.getLeft() + logoShift);
// Add a drop shadow effect to the logo
DropShadowEffect dropShadowEffect = logoLayer.getBlendingOptions().addDropShadow();
dropShadowEffect.setDistance(0);
dropShadowEffect.setSize(10);
dropShadowEffect.setOpacity((byte)50);
// Draw customized text
Layer graphicLayer = psdImage.addRegularLayer();
Graphics graphics = new Graphics(graphicLayer);
Font georgiaFont = new Font("Georgia Pro Semibold", 105, FontStyle.Regular, GraphicsUnit.Pixel);
int linesCount = text.split(System.getProperty("line.separator")).length;
int textHeight = (int)(georgiaFont.getSize() * 1.15 * linesCount + 3);
graphics.drawString(text, georgiaFont, new SolidBrush(Color.getWhite()),
110, psdImage.getHeight() - 40 - 15 - textHeight);
// Draw a rectangle filled with a blue gradient
Rectangle rectangle = new Rectangle(60,
psdImage.getHeight() - 40 - 25 - textHeight - 15, 40, 25 + textHeight + 15);
LinearGradientBrush linearGradientBrush = new LinearGradientBrush(
new Point(rectangle.getLeft(), rectangle.getTop()),
new Point(rectangle.getLeft(), rectangle.getBottom()),
Color.fromArgb(0, 106, 176), Color.fromArgb(0, 152, 255));
graphics.fillRectangle(linearGradientBrush, rectangle);
// Export the document to PNG file format
psdImage.save(outThumbnailPath, new PngOptions());
}
finally
{
psdImage.dispose();
}
}
try (Image image = Image.load(dataDir + "sample.psd");
// Convert the image into RasterImage.
RasterImage rasterImage = (RasterImage) image) {
if (rasterImage == null) {
return;
}
// Get Bounds[rectangle] of image.
Rectangle rect = image.getBounds();
// Create an instance of BilateralSmoothingFilterOptions class with size
// parameter.
BilateralSmoothingFilterOptions bilateralOptions = new BilateralSmoothingFilterOptions(3);
// Create an instance of SharpenFilterOptions class.
SharpenFilterOptions sharpenOptions = new SharpenFilterOptions();
// Supply the filters to raster image.
rasterImage.filter(rect, bilateralOptions);
rasterImage.filter(rect, sharpenOptions);
// Adjust the contrast accordingly.
rasterImage.adjustContrast(-10);
// Set brightness using Binarize Bradley
rasterImage.binarizeBradley(80);
// Save the results to output path.
rasterImage.save(dataDir + "a1_out.jpg");
}
String dataDir = Utils.getDataDir(ApplyGausWienerFilters.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "gauss_wiener_out.gif";
try (Image image = Image.load(sourceFile);
RasterImage rasterImage = (RasterImage) image) {
if (rasterImage == null) {
return;
}
// Create an instance of GaussWienerFilterOptions class and set the radius size and smooth value.
GaussWienerFilterOptions options = new GaussWienerFilterOptions(12, 3);
options.setGrayscale(true);
// Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
rasterImage.filter(image.getBounds(), options);
image.save(destName, new GifOptions());
}
String dataDir = Utils.getDataDir(ApplyGausWienerFiltersForColorImage.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "gauss_wiener_color_out.gif";
try (Image image = Image.load(sourceFile);
// Cast the image into RasterImage
RasterImage rasterImage = (RasterImage) image) {
if (rasterImage == null) {
return;
}
// Create an instance of GaussWienerFilterOptions class and set the radius size and smooth value.
GaussWienerFilterOptions options = new GaussWienerFilterOptions(5, 1.5);
options.setBrightness(1);
// Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
rasterImage.filter(image.getBounds(), options);
image.save(destName, new GifOptions());
}
String dataDir = Utils.getDataDir(ApplyMedianAndWienerFilters.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "median_test_denoise_out.gif";
try (Image image = Image.load(sourceFile);
// Cast the image into RasterImage
RasterImage rasterImage = (RasterImage) image) {
if (rasterImage == null) {
return;
}
// Create an instance of MedianFilterOptions class and set the size, Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
MedianFilterOptions options = new MedianFilterOptions(4);
rasterImage.filter(image.getBounds(), options);
image.save(destName, new GifOptions());
}
String dataDir = Utils.getDataDir(ApplyMotionWienerFilters.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "motion_filter_out.gif";
try (Image image = Image.load(sourceFile);
// Cast the image into RasterImage
RasterImage rasterImage = (RasterImage) image) {
if (rasterImage == null) {
return;
}
// Create an instance of MotionWienerFilterOptions class and set the length, smooth value and angle.
MotionWienerFilterOptions options = new MotionWienerFilterOptions(50, 9, 90);
options.setGrayscale(true);
// Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
rasterImage.filter(image.getBounds(), options);
image.save(destName, new GifOptions());
}
String dataDir = Utils.getDataDir(BinarizationWithFixedThreshold.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "BinarizationWithFixedThreshold_out.jpg";
try (Image image = Image.load(sourceFile);
RasterCachedImage rasterCachedImage = (RasterCachedImage) image) {
if (!rasterCachedImage.isCached()) {
// Cache image if not already cached
rasterCachedImage.cacheData();
}
// Binarize image with predefined fixed threshold and Save the resultant image
rasterCachedImage.binarizeFixed((byte) 100);
rasterCachedImage.save(destName, new JpegOptions());
}
String dataDir = Utils.getDataDir(BinarizationWithOtsuThreshold.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "BinarizationWithOtsuThreshold_out.jpg";
try (Image image = Image.load(sourceFile);
// Cast the image to RasterCachedImage and Check if image is cached
RasterCachedImage rasterCachedImage = (RasterCachedImage) image) {
if (!rasterCachedImage.isCached()) {
// Cache image if not already cached
rasterCachedImage.cacheData();
}
// Binarize image with Otsu Thresholding and Save the resultant image
rasterCachedImage.binarizeOtsu();
rasterCachedImage.save(destName, new JpegOptions());
}
String dataDir = Utils.getDataDir(Bradleythreshold.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "binarized_out.png";
// Load an image
try (PsdImage image = (PsdImage) Image.load(sourceFile)) {
// Define threshold value, Call BinarizeBradley method and pass the threshold value as parameter and Save the output image
double threshold = 0.15;
image.binarizeBradley(threshold);
image.save(destName, new PngOptions());
}
String dataDir = Utils.getDataDir(CMYKPSDtoCMYKTiff.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "output.tiff";
try (Image image = Image.load(sourceFile)) {
image.save(destName, new TiffOptions(TiffExpectedFormat.TiffLzwCmyk));
}
String dataDir = Utils.getDataDir(ColorConversionUsingDefaultProfiles.class) + "Conversion/";
try (PsdImage image = new PsdImage(500, 500)) {
// Fill image data.
int count = image.getWidth() * image.getHeight();
int[] pixels = new int[count];
int r = 0;
int g = 0;
int b = 0;
int channel = 0;
for (int i = 0; i < count; i++) {
if (channel % 3 == 0) {
r++;
if (r == 256) {
r = 0;
channel++;
}
} else if (channel % 3 == 1) {
g++;
if (g == 256) {
g = 0;
channel++;
}
} else {
b++;
if (b == 256) {
b = 0;
channel++;
}
}
pixels[i] = Color.fromArgb(r, g, b).toArgb();
}
// Save the newly created pixels.
image.saveArgb32Pixels(image.getBounds(), pixels);
// Save the newly created image.
image.save(dataDir + "Default.jpg");
// Update color profile.
File rgbFile = new File(dataDir + "eciRGB_v2.icc");
FileInputStream rgbInputStream = new FileInputStream(rgbFile);
StreamSource rgbprofile = new StreamSource(rgbInputStream);
File cmykFile = new File(dataDir + "ISOcoated_v2_FullGamut4.icc");
FileInputStream cmykInputStream = new FileInputStream(cmykFile);
StreamSource cmykprofile = new StreamSource(cmykInputStream);
image.setRgbColorProfile(rgbprofile);
image.setRgbColorProfile(cmykprofile);
// Save the resultant image with new YCCK profiles. You will notice differences in color values if compare the images.
JpegOptions options = new JpegOptions();
options.setColorType(JpegCompressionColorMode.Cmyk);
image.save(dataDir + "Cmyk_Default_profiles.jpg", options);
}
String dataDir = Utils.getDataDir(ColorConversionUsingICCProfiles.class) + "Conversion/";
// Create a new JpegImage.
try (PsdImage image = new PsdImage(500, 500)) {
// Fill image data.
int count = image.getWidth() * image.getHeight();
int[] pixels = new int[count];
int r = 0;
int g = 0;
int b = 0;
int channel = 0;
for (int i = 0; i < count; i++) {
if (channel % 3 == 0) {
r++;
if (r == 256) {
r = 0;
channel++;
}
} else if (channel % 3 == 1) {
g++;
if (g == 256) {
g = 0;
channel++;
}
} else {
b++;
if (b == 256) {
b = 0;
channel++;
}
}
pixels[i] = Color.fromArgb(r, g, b).toArgb();
}
// Save the newly created pixels.
image.saveArgb32Pixels(image.getBounds(), pixels);
// Save the resultant image with default Icc profiles.
image.save(dataDir + "Default_profiles.jpg");
// Update color profile.
File rgbFile = new File(dataDir + "eciRGB_v2.icc");
FileInputStream rgbInputStream = new FileInputStream(rgbFile);
StreamSource rgbprofile = new StreamSource(rgbInputStream);
File cmykFile = new File(dataDir + "ISOcoated_v2_FullGamut4.icc");
FileInputStream cmykInputStream = new FileInputStream(cmykFile);
StreamSource cmykprofile = new StreamSource(cmykInputStream);
image.setRgbColorProfile(rgbprofile);
image.setCmykColorProfile(cmykprofile);
// Save the resultant image with new YCCK profiles. You will notice differences in color values if compare the images.
JpegOptions options = new JpegOptions();
options.setColorType(JpegCompressionColorMode.Ycck);
image.save(dataDir + "Ycck_profiles.jpg", options);
}
String dataDir = Utils.getDataDir(ColorConversionUsingICCProfiles.class) + "Conversion/";
String srcPath = dataDir + "sample.psd";
String destName = dataDir + "export.png";
// Load an existing PSD image
try (RasterImage image = (RasterImage) Image.load(srcPath)) {
// Create an instance of Rectangle class by passing x,y and width,height
// Call the crop method of Image class and pass the rectangle class instance
image.crop(new Rectangle(0, 0, 350, 450));
// Create an instance of PngOptions class
PngOptions pngOptions = new PngOptions();
// Call the save method, provide output path and PngOptions to convert the PSD file to PNG and save the output
image.save(destName, pngOptions);
}
String dataDir = Utils.getDataDir(CropPSDFile.class) + "Conversion/";
// Implement correct Crop method for PSD files.
String sourceFileName = dataDir + "1.psd";
String exportPathPsd = dataDir + "CropTest.psd";
String exportPathPng = dataDir + "CropTest.png";
try (RasterImage image = (RasterImage) Image.load(sourceFileName)) {
image.crop(new Rectangle(10, 30, 100, 100));
image.save(exportPathPsd, new PsdOptions());
PngOptions options = new PngOptions();
options.setColorType(PngColorType.TruecolorWithAlpha);
image.save(exportPathPng, options);
}
String dataDir = Utils.getDataDir(ExportImagesinMultiThreadEnv.class) + "Conversion/";
String imageDataPath = dataDir + "sample.psd";
try {
FileInputStream fileStream = new FileInputStream(imageDataPath);
PsdOptions psdOptions = new PsdOptions();
// Set the source property of the imaging option class object.
psdOptions.setSource(new StreamSource(fileStream));
// Following is the sample processing on the image.
RasterImage image = (RasterImage) Image.create(psdOptions, 10, 10);
Color[] pixels = new Color[4];
for (int i = 0; i < 4; ++i) {
pixels[i] = Color.fromArgb(40, 30, 20, 10);
}
image.savePixels(new Rectangle(0, 0, 2, 2), pixels);
image.save();
} finally {
// Delete the output file.
File f = new File(imageDataPath);
if (f.exists()) {
f.delete();
}
}
String dataDir = Utils.getDataDir(GIFImageLayersToTIFF.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
// Load a PSD image and Convert the image's layers to Tiff images.
try (PsdImage image = (PsdImage) Image.load(sourceFile)) {
// Iterate through array of PSD layers
for (int i = 0; i < image.getLayers().length; i++) {
// Get PSD layer.
Layer layer = image.getLayers()[i];
// Create an instance of TIFF Option class and Save the PSD layer as TIFF image
TiffOptions objTiff = new TiffOptions(TiffExpectedFormat.TiffDeflateRgb);
layer.save("output" + i + "_out.tiff", objTiff);
}
}
String dataDir = Utils.getDataDir(GrayScaling.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "Grayscaling_out.jpg";
try (Image image = Image.load(sourceFile)) {
// Cast the image to RasterCachedImage and Check if image is cached
RasterCachedImage rasterCachedImage = (RasterCachedImage) image;
if (!rasterCachedImage.isCached()) {
// Cache image if not already cached
rasterCachedImage.cacheData();
}
// Transform image to its grayscale representation and Save the resultant image
rasterCachedImage.grayscale();
rasterCachedImage.save(destName, new JpegOptions());
}
String dataDir = Utils.getDataDir(LoadingFromStream.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "result.png";
FileInputStream inputStream = new FileInputStream(sourceFile);
try (Image image = Image.load(inputStream);
PsdImage psdImage = (PsdImage) image) {
MemoryStream stream = new MemoryStream();
FileOutputStream outputStream = new FileOutputStream(sourceFile);
psdImage.save(outputStream, new PngOptions());
}
String dataDir = Utils.getDataDir(PSDToRasterImageFormats.class) + "Conversion/";
String srcPath = dataDir + "sample.psd";
String destName = dataDir + "export";
// Load an existing PSD image as Image
try (Image image = Image.load(srcPath)) {
// Create an instance of PngOptions class
PngOptions pngOptions = new PngOptions();
// Create an instance of BmpOptions class
BmpOptions bmpOptions = new BmpOptions();
// Create an instance of GifOptions class
GifOptions gifOptions = new GifOptions();
// Create an instance of JpegOptions class
JpegOptions jpegOptions = new JpegOptions();
// Create an instance of Jpeg2000Options class
Jpeg2000Options jpeg2000Options = new Jpeg2000Options();
// Call the save method, provide output path and export options to convert PSD file to various raster file formats.
image.save(destName + ".png", pngOptions);
image.save(destName + ".bmp", bmpOptions);
image.save(destName + ".gif", gifOptions);
image.save(destName + ".jpeg", jpegOptions);
image.save(destName + ".jp2", jpeg2000Options);
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-Java
String sourceDir = Utils.GetDataDir_PSD();
String outputDir = Utils.GetDataDir_Output();
String targetFilePath = sourceDir + "text_ethalon_different_colors.psd";
String resultFilePath = outputDir + "RenderTextWithDifferentColorsInTextLayer_out.png";
PsdImage psdImage = null;
try {
psdImage = (PsdImage) Image.load(targetFilePath);
TextLayer txtLayer = (TextLayer) psdImage.getLayers()[1];
txtLayer.getTextData().updateLayerData();
PngOptions pngOptions = new PngOptions();
pngOptions.setColorType(PngColorType.TruecolorWithAlpha);
psdImage.save(resultFilePath, pngOptions);
} finally {
if (psdImage != null) psdImage.dispose();
}
public class SaveImageWorker {
/// <summary>
/// The path to the input image.
/// </summary>
private String inputPath;
/// <summary>
/// The path to the output image.
/// </summary>
private String outputPath;
/// <summary>
/// The interrupt monitor.
/// </summary>
private InterruptMonitor monitor;
/// <summary>
/// The save options.
/// </summary>
private ImageOptionsBase saveOptions;
/// <summary>
/// Initializes a new instance of the <see cref="SaveImageWorker" /> class.
/// </summary>
/// <param name="inputPath">The path to the input image.</param>
/// <param name="outputPath">The path to the output image.</param>
/// <param name="saveOptions">The save options.</param>
/// <param name="monitor">The interrupt monitor.</param>
public SaveImageWorker(String inputPath, String outputPath, ImageOptionsBase saveOptions, InterruptMonitor monitor) {
this.inputPath = inputPath;
this.outputPath = outputPath;
this.saveOptions = saveOptions;
this.monitor = monitor;
}
/// <summary>
/// Tries to convert image from one format to another. Handles interruption.
/// </summary>
public String ThreadProc() {
try (Image image = Image.load(this.inputPath)) {
InterruptMonitor.setThreadLocalInstance(this.monitor);
try {
image.save(this.outputPath, this.saveOptions);
} catch (OperationInterruptedException e) {
System.out.println("The save thread # " + Thread.currentThread().getId() + "finishes at" + getDateTime().toString());
System.out.println(e);
} catch (Exception e) {
System.out.println(e);
} finally {
InterruptMonitor.setThreadLocalInstance(null);
}
return "Hello Aspose";
}
}
}
String dataDir = Utils.getDataDir(SavingtoDisk.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "result.png";
// load PSD image and replace the non found fonts.
try (Image image = Image.load(sourceFile); PsdImage psdImage = (PsdImage) image) {
psdImage.save(destName, new PngOptions());
}
String dataDir = Utils.getDataDir(SavingtoStream.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "result.png";
// load PSD image and replace the non found fonts.
try (Image image = Image.load(sourceFile); PsdImage psdImage = (PsdImage) image) {
FileOutputStream outputStream = new FileOutputStream(sourceFile);
psdImage.save(outputStream, new PngOptions());
}
String dataDir = Utils.getDataDir(SettingforReplacingMissingFonts.class) + "Conversion/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "result.png";
PsdLoadOptions loadOptions = new PsdLoadOptions();
loadOptions.setDefaultReplacementFont("Arial");
// load PSD image and replace the non found fonts.
try (Image image = Image.load(sourceFile, loadOptions);
PsdImage psdImage = (PsdImage) image) {
PngOptions Options = new PngOptions();
Options.setColorType(PngColorType.TruecolorWithAlpha);
psdImage.save(destName, Options);
}
String dataDir = Utils.getDataDir(SupportForInterruptMonitor.class) + "Conversion/";
ImageOptionsBase saveOptions = new PngOptions();
InterruptMonitor monitor = new InterruptMonitor();
String source = dataDir + "big2.psb";
String output = dataDir + "big_out.png";
SaveImageWorker worker = new SaveImageWorker(source, output, saveOptions, monitor);
Thread thread = new Thread(worker.ThreadProc());
try {
thread.start();
// The timeout should be less than the time required for full image conversion (without interruption).
Thread.sleep(3000);
// Interrupt the process
monitor.interrupt();
System.out.println("Interrupting the save thread #" + thread.getId() + " at" + getDateTime().toString());
// Wait for interruption...
thread.join();
} finally {
// Delete the output file.
File f = new File(output);
if (f.exists()) {
f.delete();
}
}
String dataDir = Utils.getDataDir(SyncRoot.class) + "Conversion/";
// Create an instance of Stream container class and assign memory stream object.
StreamContainer streamContainer = new StreamContainer(new java.io.ByteArrayInputStream(new byte[0]));
try {
// check if the access to the stream source is synchronized.
synchronized (streamContainer.getSyncRoot()) {
// do work
// now access to streamContainer is synchronized
}
} finally {
streamContainer.dispose();
}
String dataDir = Utils.getDataDir(AddEffectAtRunTime.class) + "DrawingAndFormattingImages/";
String sourceFileName = dataDir + "ThreeRegularLayers.psd";
String exportPath = dataDir + "ThreeRegularLayersChanged.psd";
PsdLoadOptions loadOptions = new PsdLoadOptions();
loadOptions.setLoadEffectsResource(true);
try (PsdImage im = (PsdImage) Image.load(sourceFileName, loadOptions)) {
ColorOverlayEffect effect = im.getLayers()[1].getBlendingOptions().addColorOverlay();
effect.setColor(Color.getGreen());
effect.setOpacity((byte) 128);
effect.setBlendMode(BlendMode.Normal);
im.save(exportPath);
}
String dataDir = Utils.getDataDir(AdjustingBrightness.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "AdjustBrightness_out.tiff";
// Load an existing image into an instance of RasterImage class
try (Image image = Image.load(sourceFile);
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage) image) {
// Check if RasterImage is cached and Cache RasterImage for better performance
if (!rasterImage.isCached()) {
rasterImage.cacheData();
}
// Adjust the brightness
rasterImage.adjustBrightness(-50);
int[] ushort = {8, 8, 8};
// Create an instance of TiffOptions for the resultant image, Set various properties for the object of TiffOptions and Save the resultant image
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
tiffOptions.setBitsPerSample(ushort);
tiffOptions.setPhotometric(TiffPhotometrics.Rgb);
rasterImage.save(destName, tiffOptions);
}
String dataDir = Utils.getDataDir(AdjustingContrast.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "AdjustContrast_out.tiff";
// Load an existing image into an instance of RasterImage class
try (Image image = Image.load(sourceFile);
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage) image) {
// Check if RasterImage is cached and Cache RasterImage for better performance
if (!rasterImage.isCached()) {
rasterImage.cacheData();
}
// Adjust the contrast
rasterImage.adjustContrast(50);
// Create an instance of TiffOptions for the resultant image, Set various properties for the object of TiffOptions and Save the resultant image to TIFF format
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
int[] ushort = {8, 8, 8};
tiffOptions.setBitsPerSample(ushort);
tiffOptions.setPhotometric(TiffPhotometrics.Rgb);
rasterImage.save(destName, tiffOptions);
}
String dataDir = Utils.getDataDir(AdjustingGamma.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "AdjustGamma_out.tiff";
// Load an existing image into an instance of RasterImage class
try (Image image = Image.load(sourceFile);
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage) image) {
// Check if RasterImage is cached and Cache RasterImage for better performance
if (!rasterImage.isCached()) {
rasterImage.cacheData();
}
// Adjust the gamma
rasterImage.adjustGamma(2.2f, 2.2f, 2.2f);
// Create an instance of TiffOptions for the resultant image, Set various properties for the object of TiffOptions and Save the resultant image to TIFF format
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
int[] ushort = {8, 8, 8};
tiffOptions.setBitsPerSample(ushort);
tiffOptions.setPhotometric(TiffPhotometrics.Rgb);
rasterImage.save(destName, tiffOptions);
}
String dataDir = Utils.getDataDir(BlurAnImage.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "BlurAnImage_out.gif";
// Load an existing image into an instance of RasterImage class
try (Image image = Image.load(sourceFile)) {
// Convert the image into RasterImage,
//Pass Bounds[rectangle] of image and GaussianBlurFilterOptions instance to Filter method and Save the results
RasterImage rasterImage = (RasterImage) image;
rasterImage.filter(rasterImage.getBounds(), new GaussianBlurFilterOptions(15, 15));
rasterImage.save(destName, new GifOptions());
}
String dataDir = Utils.getDataDir(ColorOverLayEffect.class) + "DrawingAndFormattingImages/";
// ColorOverlay effect editing
String sourceFileName = dataDir + "ColorOverlay.psd";
String psdPathAfterChange = dataDir + "ColorOverlayChanged.psd";
PsdLoadOptions loadOptions = new PsdLoadOptions();
loadOptions.setLoadEffectsResource(true);
try (PsdImage im = (PsdImage) Image.load(sourceFileName, loadOptions)) {
ColorOverlayEffect colorOverlay = (ColorOverlayEffect) (im.getLayers()[1].getBlendingOptions().getEffects()[0]);
colorOverlay.setColor(Color.getGreen());
colorOverlay.setOpacity((byte) 128);
im.save(psdPathAfterChange);
}
String dataDir = Utils.getDataDir(CombiningImages.class) + "DrawingAndFormattingImages/";
// Create an instance of PsdOptions and set its various properties
PsdOptions imageOptions = new PsdOptions();
// Create an instance of FileCreateSource and assign it to Source property
imageOptions.setSource(new FileCreateSource(dataDir + "Two_images_result_out.psd", false));
try (Image image = Image.create(imageOptions, 600, 600)) {
// Create and initialize an instance of Graphics, Clear the image surface with white color and Draw Image
Graphics graphics = new Graphics(image);
graphics.clear(Color.getWhite());
graphics.drawImage(Image.load(dataDir + "example1.psd"), 0, 0, 300, 600);
graphics.drawImage(Image.load(dataDir + "example2.psd"), 300, 0, 300, 600);
image.save();
}
String dataDir = Utils.getDataDir(CreateXMPMetadata.class) + "DrawingAndFormattingImages/";
// Specify the size of image by defining a Rectangle
Rectangle rect = new Rectangle(0, 0, 100, 200);
// create the brand new image just for sample purposes
try (PsdImage image = new PsdImage(rect.getWidth(), rect.getHeight())) {
// create an instance of XMP-Header
XmpHeaderPi xmpHeader = new XmpHeaderPi();
xmpHeader.setGuid(dataDir);
// create an instance of Xmp-TrailerPi
XmpTrailerPi xmpTrailer = new XmpTrailerPi(true);
// create an instance of XMPmeta class to set different attributes
XmpMeta xmpMeta = new XmpMeta();
xmpMeta.addAttribute("Author", "Mr Smith");
xmpMeta.addAttribute("Description", "The fake metadata value");
// create an instance of XmpPacketWrapper that contains all metadata
XmpPacketWrapper xmpData = new XmpPacketWrapper(xmpHeader, xmpTrailer, xmpMeta);
// create an instacne of Photoshop package and set photoshop attributes
PhotoshopPackage photoshopPackage = new PhotoshopPackage();
photoshopPackage.setCity("London");
photoshopPackage.setCountry("England");
photoshopPackage.setColorMode(ColorMode.Rgb);
// add photoshop package into XMP metadata
xmpData.addPackage(photoshopPackage);
// create an instacne of DublinCore package and set dublinCore attributes
DublinCorePackage dublinCorePackage = new DublinCorePackage();
dublinCorePackage.setAuthor("Charles Bukowski");
dublinCorePackage.setTitle("Confessions of a Man Insane Enough to Live With the Beasts");
dublinCorePackage.addValue("dc:movie", "Barfly");
// add dublinCore Package into XMP metadata
xmpData.addPackage(dublinCorePackage);
MemoryStream ms = new MemoryStream();
// update XMP metadata into image
image.setXmpData(xmpData);
// Save image on the disk or in memory stream
image.save(dataDir + "create_XMP_Metadata.psd");
}
String dataDir = Utils.getDataDir(CreatingbySettingPath.class) + "DrawingAndFormattingImages/";
String desName = dataDir + "CreatingAnImageBySettingPath_out.psd";
// Creates an instance of PsdOptions and set its various properties
PsdOptions psdOptions = new PsdOptions();
psdOptions.setCompressionMethod(CompressionMethod.RLE);
// Define the source property for the instance of PsdOptions. Second boolean parameter determines if the file is temporal or not
psdOptions.setSource(new FileCreateSource(desName, false));
// Creates an instance of Image and call Create method by passing the PsdOptions object
try (Image image = Image.create(psdOptions, 500, 500)) {
image.save();
}
String dataDir = Utils.getDataDir(CreatingUsingStream.class) + "DrawingAndFormattingImages/";
String desName = dataDir + "CreatingImageUsingStream_out.bmp";
// Creates an instance of BmpOptions and set its various properties
BmpOptions imageOptions = new BmpOptions();
imageOptions.setBitsPerPixel(24);
// Create an instance of System.IO.Stream
FileCreateSource stream = new FileCreateSource(dataDir + "sample_out.bmp");
// Define the source property for the instance of BmpOptions Second boolean parameter determines if the Stream is disposed once get out of scope
imageOptions.setSource(stream);
// Creates an instance of Image and call Create method by passing the BmpOptions object
try (Image image = Image.create(imageOptions, 500, 500)) {
// Do some image processing
image.save(desName);
}
String dataDir = Utils.getDataDir(CroppingbyRectangle.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "CroppingByRectangle_out.jpg";
// Load an existing image into an instance of RasterImage class
try (RasterImage rasterImage = (RasterImage) Image.load(sourceFile)) {
if (!rasterImage.isCached()) {
rasterImage.cacheData();
}
// Create an instance of Rectangle class with desired size,
//Perform the crop operation on object of Rectangle class and Save the results to disk
Rectangle rectangle = new Rectangle(20, 20, 20, 20);
rasterImage.crop(rectangle);
rasterImage.save(destName, new JpegOptions());
}
String dataDir = Utils.getDataDir(CroppingbyShifts.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "CroppingByShifts_out.jpg";
// Load an existing image into an instance of RasterImage class
try (RasterImage rasterImage = (RasterImage) Image.load(sourceFile)) {
// 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);
rasterImage.save(destName, new JpegOptions());
}
String dataDir = Utils.getDataDir(DitheringforRasterImages.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "SampleImage_out.bmp";
// Load an existing image into an instance of RasterImage class
try (PsdImage image = (PsdImage) Image.load(sourceFile)) {
// Peform Floyd Steinberg dithering on the current image and Save the resultant image
image.dither(DitheringMethod.ThresholdDithering, 4);
image.save(destName, new BmpOptions());
}
String dataDir = Utils.getDataDir(ExpandAndCropImages.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "example1.psd";
String destName = dataDir + "jpeg_out.jpg";
try (RasterImage rasterImage = (RasterImage) Image.load(sourceFile)) {
rasterImage.cacheData();
// Create an instance of Rectangle class and define X,Y and Width, height of the rectangle, and Save output image
Rectangle destRect = new Rectangle(-200, -200, 300, 300);
rasterImage.save(destName, new JpegOptions(), destRect);
}
String dataDir = Utils.getDataDir(FontReplacement.class) + "DrawingAndFormattingImages/";
// Load an image in an instance of image and setting default replacement font.
PsdLoadOptions psdLoadOptions = new PsdLoadOptions();
psdLoadOptions.setDefaultReplacementFont("Arial");
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "Cloud_AzPlat_Banner3A_SB_EN_US_160x600_chinese_font.psd", psdLoadOptions)) {
PngOptions pngOptions = new PngOptions();
psdImage.save(dataDir + "replaced_font.png", pngOptions);
}
String dataDir = Utils.getDataDir(ForceFontCache.class) + "DrawingAndFormattingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "sample.psd")) {
image.save(dataDir + "NoFont.psd");
}
System.out.println("You have 2 minutes to install the font");
Thread.sleep(2 * 60 * 1000);
OpenTypeFontsCache.updateCache();
try (PsdImage image1 = (PsdImage) Image.load(dataDir + "sample.psd")) {
image1.save(dataDir + "HasFont.psd");
}
String dataDir = Utils.getDataDir(ImplementBicubicResampler.class) + "DrawingAndFormattingImages/";
String filePath = dataDir + "sample_bicubic.psd";
String destNameCubicConvolution = dataDir + "ResamplerCubicConvolutionStripes_after.psd";
try (PsdImage image = (PsdImage) Image.load(filePath)) {
image.resize(300, 300, ResizeType.CubicConvolution);
image.save(destNameCubicConvolution, new PsdOptions(image));
String destNameBell = dataDir + "ResamplerBellStripes_after.psd";
}
try (PsdImage imageBellStripes = (PsdImage) Image.load(filePath)) {
imageBellStripes.resize(300, 300, ResizeType.Bell);
imageBellStripes.save(destNameCubicConvolution, new PsdOptions(imageBellStripes));
}
String dataDir = Utils.getDataDir(ImplementLossyGIFCompressor.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "anim_lossy-200.gif";
// Load an existing image into an instance of RasterImage class
try (Image image = Image.load(sourceFile)) {
GifOptions gifExport = new GifOptions();
gifExport.setMaxDiff(80);
image.save(dataDir + "anim_lossy-80.gif", gifExport);
gifExport.setMaxDiff(200);
image.save(destName, gifExport);
}
String dataDir = Utils.getDataDir(InvertAdjustmentLayer.class) + "DrawingAndFormattingImages/";
String filePath = dataDir + "InvertStripes_before.psd";
String outputPath = dataDir + "InvertStripes_after.psd";
try (PsdImage im = (PsdImage) Image.load(filePath)) {
im.addInvertAdjustmentLayer();
im.save(outputPath);
}
String dataDir = Utils.getDataDir(RenderingColorEffect.class) + "DrawingAndFormattingImages/";
String sourceFileName = dataDir + "ColorOverlay.psd";
String pngExportPath = dataDir + "ColorOverlayresult.png";
PsdLoadOptions loadOptions = new PsdLoadOptions();
loadOptions.setLoadEffectsResource(true);
try (PsdImage im = (PsdImage) Image.load(sourceFileName, loadOptions)) {
ColorOverlayEffect colorOverlay = (ColorOverlayEffect) (im.getLayers()[1].getBlendingOptions().getEffects()[0]);
PngOptions saveOptions = new PngOptions();
saveOptions.setColorType(PngColorType.TruecolorWithAlpha);
im.save(pngExportPath, saveOptions);
}
String dataDir = Utils.getDataDir(RenderingDropShadow.class) + "DrawingAndFormattingImages/";
String sourceFileName = dataDir + "Shadow.psd";
String pngExportPath = dataDir + "Shadowchanged1.png";
PsdLoadOptions loadOptions = new PsdLoadOptions();
loadOptions.setLoadEffectsResource(true);
try (PsdImage im = (PsdImage) Image.load(sourceFileName, loadOptions)) {
DropShadowEffect shadowEffect = (DropShadowEffect) (im.getLayers()[1].getBlendingOptions().getEffects()[0]);
Assert.areEqual(Color.getBlack(), shadowEffect.getColor());
Assert.areEqual(255, shadowEffect.getOpacity());
Assert.areEqual(3, shadowEffect.getDistance());
Assert.areEqual(7, shadowEffect.getSize());
Assert.areEqual(true, shadowEffect.getUseGlobalLight());
Assert.areEqual(90, shadowEffect.getAngle());
Assert.areEqual(0, shadowEffect.getSpread());
Assert.areEqual(0, shadowEffect.getNoise());
// Save PNG
PngOptions saveOptions = new PngOptions();
saveOptions.setColorType(PngColorType.TruecolorWithAlpha);
im.save(pngExportPath, saveOptions);
}
String dataDir = Utils.getDataDir(ResizeImageProportionally.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "SimpleResizeImageProportionally_out.png";
try (Image image = Image.load(sourceFile)) {
if (!image.isCached()) {
image.cacheData();
}
// Specifying width and height
int newWidth = image.getWidth() / 2;
image.resizeWidthProportionally(newWidth);
int newHeight = image.getHeight() / 2;
image.resizeHeightProportionally(newHeight);
image.save(destName, new PngOptions());
}
String dataDir = Utils.getDataDir(ResizingwithResizeTypeEnumeration.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "ResizingwithResizeTypeEnumeration_out.jpg";
// Load an existing image into an instance of RasterImage class
try (Image image = Image.load(sourceFile)) {
image.resize(300, 300, ResizeType.LanczosResample);
image.save(destName, new JpegOptions());
}
String dataDir = Utils.getDataDir(RotatinganImage.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "RotatingAnImage_out.jpg";
// Load an existing image into an instance of RasterImage class
try (Image image = Image.load(sourceFile)) {
image.rotateFlip(RotateFlipType.Rotate270FlipNone);
image.save(destName, new JpegOptions());
}
String dataDir = Utils.getDataDir(RotatinganImageonaSpecificAngle.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "RotatingImageOnSpecificAngle_out.jpg";
try (RasterImage image = (RasterImage) Image.load(sourceFile)) {
// Before rotation, the image should be cached for better performance
if (!image.isCached()) {
image.cacheData();
}
// Perform the rotation on 20 degree while keeping the image size proportional with red background color and Save the result to a new file
image.rotate(20f, true, Color.getRed());
image.save(destName, new JpegOptions());
}
String dataDir = Utils.getDataDir(SimpleResizing.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "SimpleResizing_out.jpg";
// Load an existing image into an instance of RasterImage class
try (Image image = Image.load(sourceFile)) {
image.resize(300, 300);
image.save(destName, new JpegOptions());
}
String[] files = new String[]
{
"Normal",
"Dissolve",
"Darken",
"Multiply",
"ColorBurn",
"LinearBurn",
"DarkerColor",
"Lighten",
"Screen",
"ColorDodge",
"LinearDodgeAdd",
"LightenColor",
"Overlay",
"SoftLight",
"HardLight",
"VividLight",
"LinearLight",
"PinLight",
"HardMix",
"Difference",
"Exclusion",
"Subtract",
"Divide",
"Hue",
"Saturation",
"Color",
"Luminosity",
};
for (int i = 0; i < files.length; i++) {
try (PsdImage im = (PsdImage) Image.load(dataDir + files[i] + ".psd")) {
// Export to PNG
PngOptions saveOptions = new PngOptions();
saveOptions.setColorType(PngColorType.TruecolorWithAlpha);
String pngExportPath100 = dataDir + "BlendMode" + files[i] + "_Test100.png";
im.save(pngExportPath100, saveOptions);
// Set opacity 50%
im.getLayers()[1].setOpacity((byte) 127);
String pngExportPath50 = dataDir + "BlendMode" + files[i] + "_Test50.png";
im.save(pngExportPath50, saveOptions);
}
}
String dataDir = Utils.getDataDir(SupportShadowEffect.class) + "DrawingAndFormattingImages/";
String sourceFileName = dataDir + "Shadow.psd";
String psdPathAfterChange = dataDir + "ShadowChanged.psd";
PsdLoadOptions loadOptions = new PsdLoadOptions();
loadOptions.setLoadEffectsResource(true);
try (PsdImage im = (PsdImage) Image.load(sourceFileName, loadOptions)) {
DropShadowEffect shadowEffect = (DropShadowEffect) (im.getLayers()[1].getBlendingOptions().getEffects()[0]);
Assert.areEqual(Color.getBlack(), shadowEffect.getColor());
Assert.areEqual(255, shadowEffect.getOpacity());
Assert.areEqual(3, shadowEffect.getDistance());
Assert.areEqual(7, shadowEffect.getSize());
Assert.areEqual(true, shadowEffect.getUseGlobalLight());
Assert.areEqual(90, shadowEffect.getAngle());
Assert.areEqual(0, shadowEffect.getSpread());
Assert.areEqual(0, shadowEffect.getNoise());
shadowEffect.setColor(Color.getGreen());
shadowEffect.setOpacity((byte) 128);
shadowEffect.setDistance(11);
shadowEffect.setUseGlobalLight(false);
shadowEffect.setSize(9);
shadowEffect.setAngle(45);
shadowEffect.setSpread(3);
shadowEffect.setNoise(50);
im.save(psdPathAfterChange);
}
String dataDir = Utils.getDataDir(VerifyImageTransparency.class) + "DrawingAndFormattingImages/";
String sourceFile = dataDir + "sample.psd";
String destName = dataDir + "AdjustBrightness_out.tiff";
// Load an existing image into an instance of RasterImage class
try (PsdImage image = (PsdImage) Image.load(sourceFile)) {
float opacity = image.getImageOpacity();
System.out.println(opacity);
if (opacity == 0) {
// The image is fully transparent.
}
}
String dataDir = Utils.getDataDir(AddGradientEffects.class) + "DrawingImages/";
// Gradient overlay effect. Example
String sourceFileName = dataDir + "GradientOverlay.psd";
String exportPath = dataDir + "GradientOverlayChanged.psd";
PsdLoadOptions loadOptions = new PsdLoadOptions();
loadOptions.setLoadEffectsResource(true);
try (PsdImage im = (PsdImage) Image.load(sourceFileName, loadOptions)) {
GradientOverlayEffect gradientOverlay = (GradientOverlayEffect) im.getLayers()[1].getBlendingOptions().getEffects()[0];
Assert.areEqual(BlendMode.Normal, gradientOverlay.getBlendMode());
Assert.areEqual(255, gradientOverlay.getOpacity());
Assert.areEqual(true, gradientOverlay.isVisible());
GradientFillSettings settings = gradientOverlay.getSettings();
Assert.areEqual(Color.getEmpty(), settings.getColor());
Assert.areEqual(FillType.Gradient, settings.getFillType());
Assert.areEqual(true, settings.getAlignWithLayer());
Assert.areEqual(GradientType.Linear, settings.getGradientType());
Assert.IsTrue(Math.abs(33 - settings.getAngle()) < 0.001, "Angle is incorrect");
Assert.areEqual(false, settings.getDither());
Assert.areEqual(Math.abs(129 - settings.getHorizontalOffset()) < 0.001, "Horizontal offset is incorrect");
Assert.IsTrue(Math.abs(156 - settings.getVerticalOffset()) < 0.001, "Vertical offset is incorrect");
Assert.areEqual(false, settings.getReverse());
// Color Points
IGradientColorPoint[] colorPoints = settings.getColorPoints();
Assert.areEqual(3, colorPoints.length);
Assert.areEqual(Color.fromArgb(9, 0, 178), colorPoints[0].getColor());
Assert.areEqual(0, colorPoints[0].getLocation());
Assert.areEqual(50, colorPoints[0].getMedianPointLocation());
Assert.areEqual(Color.getRed(), colorPoints[1].getColor());
Assert.areEqual(2048, colorPoints[1].getLocation());
Assert.areEqual(50, colorPoints[1].getMedianPointLocation());
Assert.areEqual(Color.fromArgb(255, 252, 0), colorPoints[2].getColor());
Assert.areEqual(4096, colorPoints[2].getLocation());
Assert.areEqual(50, colorPoints[2].getMedianPointLocation());
// Transparency points
IGradientTransparencyPoint[] transparencyPoints = settings.getTransparencyPoints();
Assert.areEqual(2, transparencyPoints.length);
Assert.areEqual(0, transparencyPoints[0].getLocation());
Assert.areEqual(50, transparencyPoints[0].getMedianPointLocation());
Assert.areEqual(100, transparencyPoints[0].getOpacity());
Assert.areEqual(4096, transparencyPoints[1].getLocation());
Assert.areEqual(50, transparencyPoints[1].getMedianPointLocation());
Assert.areEqual(100, transparencyPoints[1].getOpacity());
// Test editing
settings.setColor(Color.getGreen());
gradientOverlay.setOpacity((byte) 193);
gradientOverlay.setBlendMode(BlendMode.Lighten);
settings.setAlignWithLayer(false);
settings.setGradientType(GradientType.Radial);
settings.setAngle(45);
settings.setDither(true);
settings.setHorizontalOffset(15);
settings.setVerticalOffset(11);
settings.setReverse(true);
// Add new color point
GradientColorPoint colorPoint = settings.addColorPoint();
colorPoint.setColor(Color.getGreen());
colorPoint.setLocation(4096);
colorPoint.setMedianPointLocation(75);
// Change location of previous point
settings.getColorPoints()[2].setLocation(3000);
// Add new transparency point
GradientTransparencyPoint transparencyPoint = settings.addTransparencyPoint();
transparencyPoint.setOpacity(25);
transparencyPoint.setMedianPointLocation(25);
transparencyPoint.setLocation(4096);
// Change location of previous transparency point
settings.getTransparencyPoints()[1].setLocation(2315);
im.save(exportPath);
}
// Test file after edit
try (PsdImage img = (PsdImage) Image.load(sourceFileName, loadOptions)) {
GradientOverlayEffect gradientOverlayEffect = (GradientOverlayEffect) img.getLayers()[1].getBlendingOptions().getEffects()[0];
Assert.areEqual(BlendMode.Lighten, gradientOverlayEffect.getBlendMode());
Assert.areEqual(193, gradientOverlayEffect.getOpacity());
Assert.areEqual(true, gradientOverlayEffect.isVisible());
GradientFillSettings fillSettings = gradientOverlayEffect.getSettings();
Assert.areEqual(Color.getEmpty(), fillSettings.getColor());
Assert.areEqual(FillType.Gradient, fillSettings.getFillType());
// Check color points
Assert.areEqual(4, fillSettings.getColorPoints().length);
IGradientColorPoint point = fillSettings.getColorPoints()[0];
Assert.areEqual(50, point.getMedianPointLocation());
Assert.areEqual(Color.fromArgb(9, 0, 178), point.getColor());
Assert.areEqual(0, point.getLocation());
point = fillSettings.getColorPoints()[1];
Assert.areEqual(50, point.getMedianPointLocation());
Assert.areEqual(Color.getRed(), point.getColor());
Assert.areEqual(2048, point.getLocation());
point = fillSettings.getColorPoints()[2];
Assert.areEqual(50, point.getMedianPointLocation());
Assert.areEqual(Color.fromArgb(255, 252, 0), point.getColor());
Assert.areEqual(3000, point.getLocation());
// Check transparent points
Assert.areEqual(3, fillSettings.getTransparencyPoints().length);
IGradientTransparencyPoint transparencyPoint1 = fillSettings.getTransparencyPoints()[0];
Assert.areEqual(50, transparencyPoint1.getMedianPointLocation());
Assert.areEqual(100, transparencyPoint1.getOpacity());
Assert.areEqual(0, transparencyPoint1.getLocation());
transparencyPoint1 = fillSettings.getTransparencyPoints()[1];
Assert.areEqual(50, transparencyPoint.getMedianPointLocation());
Assert.areEqual(100, transparencyPoint.getOpacity());
Assert.areEqual(2315, transparencyPoint.getLocation());
}
String dataDir = Utils.getDataDir(AddNewRegularLayerToPSD.class) + "DrawingImages/";
// Make ability to add the newly generated regular layer to PsdImage
String sourceFileName = dataDir + "OneLayer.psd";
String exportPath = dataDir + "OneLayerEdited.psd";
String exportPathPng = dataDir + "OneLayerEdited.png";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
// Preparing two int arrays
int[] data1 = new int[2500];
int[] data2 = new int[2500];
Rectangle rect1 = new Rectangle(0, 0, 50, 50);
Rectangle rect2 = new Rectangle(0, 0, 100, 25);
for (int i = 0; i < 2500; i++) {
data1[i] = -10000000;
data2[i] = -10000000;
}
Layer layer1 = im.addRegularLayer();
layer1.setLeft(25);
layer1.setTop(25);
layer1.setRight(75);
layer1.setBottom(75);
layer1.saveArgb32Pixels(rect1, data1);
Layer layer2 = im.addRegularLayer();
layer2.setLeft(25);
layer2.setTop(150);
layer2.setRight(1255);
layer2.setBottom(175);
layer2.saveArgb32Pixels(rect2, data2);
// Save psd
im.save(exportPath, new PsdOptions());
// Save png
im.save(exportPathPng, new PngOptions());
}
String dataDir = Utils.getDataDir(AddPatternEffects.class) + "DrawingImages/";
// Pattern overlay effect. Example
String sourceFileName = dataDir + "PatternOverlay.psd";
String exportPath = dataDir + "PatternOverlayChanged.psd";
int[] newPattern = new int[]
{
Color.getAqua().toArgb(), Color.getRed().toArgb(), Color.getRed().toArgb(), Color.getAqua().toArgb(),
Color.getAqua().toArgb(), Color.getWhite().toArgb(), Color.getWhite().toArgb(), Color.getAqua().toArgb(),
};
Rectangle newPatternBounds = new Rectangle(0, 0, 4, 2);
UUID guid = UUID.randomUUID();
String newPatternName = "$$$/Presets/Patterns/Pattern=Some new pattern name\0";
PsdLoadOptions loadOptions = new PsdLoadOptions();
loadOptions.setLoadEffectsResource(true);
try (PsdImage im = (PsdImage) Image.load(sourceFileName, loadOptions)) {
PatternOverlayEffect patternOverlay = (PatternOverlayEffect) im.getLayers()[1].getBlendingOptions().getEffects()[0];
Assert.areEqual(BlendMode.Normal, patternOverlay.getBlendMode());
Assert.areEqual(127, patternOverlay.getOpacity());
Assert.areEqual(true, patternOverlay.isVisible());
PatternFillSettings settings = patternOverlay.getSettings();
Assert.areEqual(Color.getEmpty(), settings.getColor());
Assert.areEqual(FillType.Pattern, settings.getFillType());
Assert.areEqual("85163837-eb9e-5b43-86fb-e6d5963ea29a\0", settings.getPatternId());
Assert.areEqual("$$$/Presets/Patterns/OpticalSquares=Optical Squares\0", settings.getPatternName());
Assert.areEqual(null, settings.getPointType());
Assert.areEqual(100, settings.getScale());
Assert.areEqual(false, settings.getLinked());
Assert.IsTrue(Math.abs(0 - settings.getHorizontalOffset()) < 0.001, "Horizontal offset is incorrect");
Assert.IsTrue(Math.abs(0 - settings.getVerticalOffset()) < 0.001, "Vertical offset is incorrect");
// Test editing
settings.setColor(Color.getGreen());
patternOverlay.setOpacity((byte) 193);
patternOverlay.setBlendMode(BlendMode.Difference);
settings.setHorizontalOffset(15);
settings.setVerticalOffset(11);
PattResource resource;
for (int i = 0; i < im.getGlobalLayerResources().length; i++) {
if (im.getGlobalLayerResources()[i] instanceof PattResource) {
resource = (PattResource) im.getGlobalLayerResources()[i];
resource.setPatternId(guid.toString());
resource.setName(newPatternName);
resource.setPattern(newPattern, newPatternBounds);
}
}
settings.setPatternName(newPatternName);
settings.setPatternId(guid.toString() + "\0");
im.save(exportPath);
}
// Test file after edit
try (PsdImage img = (PsdImage) Image.load(sourceFileName, loadOptions)) {
PatternOverlayEffect patternOverlayEffect = (PatternOverlayEffect) img.getLayers()[1].getBlendingOptions().getEffects()[0];
try {
Assert.areEqual(BlendMode.Difference, patternOverlayEffect.getBlendMode());
Assert.areEqual(193, patternOverlayEffect.getOpacity());
Assert.areEqual(true, patternOverlayEffect.isVisible());
PatternFillSettings fillSetting = patternOverlayEffect.getSettings();
Assert.areEqual(Color.getEmpty(), fillSetting.getColor());
Assert.areEqual(FillType.Pattern, fillSetting.getFillType());
PattResource resources = null;
for (int i = 0; i < img.getGlobalLayerResources().length; i++) {
if (img.getGlobalLayerResources()[i] instanceof PattResource) {
resources = (PattResource) img.getGlobalLayerResources()[i];
}
}
// Check the pattern data
Assert.areEqual(newPattern, resources.getPatternData());
Assert.areEqual(newPatternBounds, new Rectangle(0, 0, resources.getWidth(), resources.getHeight()));
Assert.areEqual(guid.toString(), resources.getPatternId());
Assert.areEqual(newPatternName, resources.getName());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
String dataDir = Utils.getDataDir(AddSignatureToImage.class) + "DrawingImages/";
// Create an instance of Image and load the primary image
try (Image canvas = Image.load(dataDir + "layers.psd");
// Create another instance of Image and load the secondary image containing the signature graphics
Image signature = Image.load(dataDir + "sample.psd")) {
// Create an instance of Graphics class and initialize it using the object of the primary image
Graphics graphics = new Graphics(canvas);
// Call the DrawImage method while passing the instance of secondary image and appropriate location. The following snippet tries to draw the secondary image at the right bottom of the primary image
graphics.drawImage(signature, new Point(canvas.getHeight() - signature.getHeight(), canvas.getWidth() - signature.getWidth()));
canvas.save(dataDir + "AddSignatureToImage_out.png", new PngOptions());
}
String dataDir = Utils.getDataDir(AddStrokeLayerColor.class) + "DrawingImages/";
// Stroke effect. FillType - Color. Example
String sourceFileName = dataDir + "Stroke.psd";
String exportPath = dataDir + "StrokeGradientChanged.psd";
PsdLoadOptions loadOptions = new PsdLoadOptions();
loadOptions.setLoadEffectsResource(true);
try (PsdImage im = (PsdImage) Image.load(sourceFileName, loadOptions)) {
StrokeEffect colorStroke = (StrokeEffect) im.getLayers()[1].getBlendingOptions().getEffects()[0];
Assert.areEqual(BlendMode.Normal, colorStroke.getBlendMode());
Assert.areEqual(255, colorStroke.getOpacity());
Assert.areEqual(true, colorStroke.isVisible());
ColorFillSettings fillSettings = (ColorFillSettings) colorStroke.getFillSettings();
Assert.areEqual(Color.getBlack(), fillSettings.getColor());
Assert.areEqual(FillType.Color, fillSettings.getFillType());
fillSettings.setColor(Color.getYellow());
colorStroke.setOpacity((byte) 127);
colorStroke.setBlendMode(BlendMode.Color);
im.save(exportPath);
}
String dataDir = Utils.getDataDir(AddStrokeLayerGradient.class) + "DrawingImages/";
// Stroke effect. FillType - Gradient. Example
String sourceFileName = dataDir + "Stroke.psd";
String exportPath = dataDir + "StrokeGradientChanged.psd";
PsdLoadOptions loadOptions = new PsdLoadOptions();
loadOptions.setLoadEffectsResource(true);
try (PsdImage im = (PsdImage) Image.load(sourceFileName, loadOptions)) {
StrokeEffect gradientStroke = (StrokeEffect) im.getLayers()[2].getBlendingOptions().getEffects()[0];
Assert.areEqual(BlendMode.Normal, gradientStroke.getBlendMode());
Assert.areEqual(255, gradientStroke.getOpacity());
Assert.areEqual(true, gradientStroke.isVisible());
GradientFillSettings fillSettings = (GradientFillSettings) gradientStroke.getFillSettings();
Assert.areEqual(Color.getBlack(), fillSettings.getColor());
Assert.areEqual(FillType.Gradient, fillSettings.getFillType());
Assert.areEqual(true, fillSettings.getAlignWithLayer());
Assert.areEqual(GradientType.Linear, fillSettings.getGradientType());
Assert.IsTrue(Math.abs(90 - fillSettings.getAngle()) < 0.001, "Angle is incorrect");
Assert.areEqual(false, fillSettings.getDither());
Assert.IsTrue(Math.abs(0 - fillSettings.getHorizontalOffset()) < 0.001, "Horizontal offset is incorrect");
Assert.IsTrue(Math.abs(0 - fillSettings.getVerticalOffset()) < 0.001, "Vertical offset is incorrect");
Assert.areEqual(false, fillSettings.getReverse());
// Color Points
IGradientColorPoint[] colorPoints = fillSettings.getColorPoints();
Assert.areEqual(2, colorPoints.length);
Assert.areEqual(Color.getBlack(), colorPoints[0].getColor());
Assert.areEqual(0, colorPoints[0].getLocation());
Assert.areEqual(50, colorPoints[0].getMedianPointLocation());
Assert.areEqual(Color.getWhite(), colorPoints[1].getColor());
Assert.areEqual(4096, colorPoints[1].getLocation());
Assert.areEqual(50, colorPoints[1].getMedianPointLocation());
// Transparency points
IGradientTransparencyPoint[] transparencyPoints = fillSettings.getTransparencyPoints();
Assert.areEqual(2, transparencyPoints.length);
Assert.areEqual(0, transparencyPoints[0].getLocation());
Assert.areEqual(50, transparencyPoints[0].getMedianPointLocation());
Assert.areEqual(100, transparencyPoints[0].getOpacity());
Assert.areEqual(4096, transparencyPoints[1].getLocation());
Assert.areEqual(50, transparencyPoints[1].getMedianPointLocation());
Assert.areEqual(100, transparencyPoints[1].getOpacity());
// Test editing
fillSettings.setColor(Color.getGreen());
gradientStroke.setOpacity((byte) 127);
gradientStroke.setBlendMode(BlendMode.Color);
fillSettings.setAlignWithLayer(false);
fillSettings.setGradientType(GradientType.Radial);
fillSettings.setAngle(45);
fillSettings.setDither(true);
fillSettings.setHorizontalOffset(15);
fillSettings.setVerticalOffset(11);
fillSettings.setReverse(true);
// Add new color point
GradientColorPoint colorPoint = fillSettings.addColorPoint();
colorPoint.setColor(Color.getGreen());
colorPoint.setLocation(4096);
colorPoint.setMedianPointLocation(75);
// Change location of previous point
fillSettings.getColorPoints()[1].setLocation(1899);
// Add new transparency point
GradientTransparencyPoint transparencyPoint = fillSettings.addTransparencyPoint();
transparencyPoint.setOpacity(25);
transparencyPoint.setMedianPointLocation(25);
transparencyPoint.setLocation(4096);
// Change location of previous transparency point
fillSettings.getTransparencyPoints()[1].setLocation(2411);
im.save(exportPath);
}
// Test file after edit
try (PsdImage img = (PsdImage) Image.load(exportPath, loadOptions)) {
StrokeEffect gradientStrokeEffect = (StrokeEffect) img.getLayers()[2].getBlendingOptions().getEffects()[0];
Assert.areEqual(BlendMode.Color, gradientStrokeEffect.getBlendMode());
Assert.areEqual(127, gradientStrokeEffect.getOpacity());
Assert.areEqual(true, gradientStrokeEffect.isVisible());
GradientFillSettings fillSetting = (GradientFillSettings) gradientStrokeEffect.getFillSettings();
Assert.areEqual(Color.getGreen(), fillSetting.getColor());
Assert.areEqual(FillType.Gradient, fillSetting.getFillType());
// Check color points
Assert.areEqual(3, fillSetting.getColorPoints().length);
IGradientColorPoint point = fillSetting.getColorPoints()[0];
Assert.areEqual(50, point.getMedianPointLocation());
Assert.areEqual(Color.getBlack(), point.getColor());
Assert.areEqual(0, point.getLocation());
point = fillSettings.getColorPoints()[1];
Assert.areEqual(50, point.getMedianPointLocation());
Assert.areEqual(Color.getWhite(), point.getColor());
Assert.areEqual(1899, point.getLocation());
point = fillSettings.getColorPoints()[2];
Assert.areEqual(75, point.getMedianPointLocation());
Assert.areEqual(Color.getGreen(), point.getColor());
Assert.areEqual(4096, point.getLocation());
// Check transparent points
Assert.areEqual(3, fillSettings.getTransparencyPoints().length);
IGradientTransparencyPoint transparencyPoint1 = fillSettings.getTransparencyPoints()[0];
Assert.areEqual(50, transparencyPoint1.getMedianPointLocation());
Assert.areEqual(100, transparencyPoint1.getOpacity());
Assert.areEqual(0, transparencyPoint1.getLocation());
transparencyPoint1 = fillSettings.getTransparencyPoints()[1];
Assert.areEqual(50, transparencyPoint.getMedianPointLocation());
Assert.areEqual(100, transparencyPoint.getOpacity());
Assert.areEqual(2411, transparencyPoint.getLocation());
transparencyPoint1 = fillSettings.getTransparencyPoints()[2];
Assert.areEqual(25, transparencyPoint.getMedianPointLocation());
Assert.areEqual(25, transparencyPoint.getOpacity());
Assert.areEqual(4096, transparencyPoint.getLocation());
}
String dataDir = Utils.getDataDir(AddStrokeLayerPattern.class) + "DrawingImages/";
// Stroke effect. FillType - Pattern. Example
String sourceFileName = dataDir + "Stroke.psd";
String exportPath = dataDir + "StrokePatternChanged.psd";
PsdLoadOptions loadOptions = new PsdLoadOptions();
loadOptions.setLoadEffectsResource(true);
// Preparing new data
int[] newPattern = new int[]
{
Color.getAqua().toArgb(), Color.getRed().toArgb(), Color.getRed().toArgb(), Color.getAqua().toArgb(),
Color.getAqua().toArgb(), Color.getWhite().toArgb(), Color.getWhite().toArgb(), Color.getAqua().toArgb(),
Color.getAqua().toArgb(), Color.getWhite().toArgb(), Color.getWhite().toArgb(), Color.getAqua().toArgb(),
Color.getAqua().toArgb(), Color.getRed().toArgb(), Color.getRed().toArgb(), Color.getAqua().toArgb(),
};
Rectangle newPatternBounds = new Rectangle(0, 0, 4, 4);
UUID guid = UUID.randomUUID();
try (PsdImage im = (PsdImage) Image.load(sourceFileName, loadOptions)) {
StrokeEffect patternStroke = (StrokeEffect) im.getLayers()[3].getBlendingOptions().getEffects()[0];
Assert.areEqual(BlendMode.Normal, patternStroke.getBlendMode());
Assert.areEqual(255, patternStroke.getOpacity());
Assert.areEqual(true, patternStroke.isVisible());
PatternFillSettings fillSettings = (PatternFillSettings) patternStroke.getFillSettings();
Assert.areEqual(FillType.Pattern, fillSettings.getFillType());
patternStroke.setOpacity((byte) 127);
patternStroke.setBlendMode(BlendMode.Color);
PattResource resource;
for (int i = 0; i < im.getGlobalLayerResources().length; i++) {
if (im.getGlobalLayerResources()[i] instanceof PattResource) {
resource = (PattResource) im.getGlobalLayerResources()[i];
resource.setPatternId(guid.toString());
resource.setName("$$$/Presets/Patterns/HorizontalLine1=Horizontal Line 9\0");
resource.setPattern(newPattern, newPatternBounds);
}
}
((PatternFillSettings) patternStroke.getFillSettings()).setPatternName("$$$/Presets/Patterns/HorizontalLine1=Horizontal Line 9\0");
((PatternFillSettings) patternStroke.getFillSettings()).setPatternId(guid.toString() + "\0");
im.save(exportPath);
}
// Test file after edit
try (PsdImage img = (PsdImage) Image.load(sourceFileName, loadOptions)) {
StrokeEffect patternStrokeEffect = (StrokeEffect) img.getLayers()[3].getBlendingOptions().getEffects()[0];
PattResource resource1 = null;
for (int i = 0; i < img.getGlobalLayerResources().length; i++) {
if (img.getGlobalLayerResources()[i] instanceof PattResource) {
resource1 = (PattResource) img.getGlobalLayerResources()[i];
}
}
try {
// Check the pattern data
Assert.areEqual(newPattern, resource1.getPatternData());
Assert.areEqual(newPatternBounds, new Rectangle(0, 0, resource1.getWidth(), resource1.getHeight()));
Assert.areEqual(guid.toString(), resource1.getPatternId());
Assert.areEqual(BlendMode.Color, patternStrokeEffect.getBlendMode());
Assert.areEqual(127, patternStrokeEffect.getOpacity());
Assert.areEqual(true, patternStrokeEffect.isVisible());
PatternFillSettings fillSettings1 = (PatternFillSettings) patternStrokeEffect.getFillSettings();
Assert.areEqual(FillType.Pattern, fillSettings1.getFillType());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
String dataDir = Utils.getDataDir(CoreDrawingFeatures.class) + "DrawingImages/";
// Create an instance of BmpOptions and set its various properties
String loadpath = dataDir + "sample.psd";
String outpath = dataDir + "CoreDrawingFeatures.bmp";
// Create an instance of Image
try (PsdImage image = new PsdImage(loadpath)) {
// load pixels
int[] pixels = image.loadArgb32Pixels(new Rectangle(0, 0, 100, 10));
for (int i = 0; i < pixels.length; i++) {
// specify pixel color value (gradient in this case).
pixels[i] = i;
}
// save modified pixels.
image.saveArgb32Pixels(new Rectangle(0, 0, 100, 10), pixels);
// export image to bmp file format.
image.save(outpath, new BmpOptions());
}
String dataDir = Utils.getDataDir(DrawingArc.class) + "DrawingImages/";
// Create an instance of BmpOptions and set its various properties
String outpath = dataDir + "Arc.bmp";
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.setBitsPerPixel(32);
// Create an instance of Image
try (Image image = new PsdImage(100, 100)) {
// Create and initialize an instance of Graphics class and clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.clear(Color.getYellow());
// Draw an arc shape by specifying the Pen object having red black color and coordinates, height, width, start & end angles
int width = 100;
int height = 200;
int startAngle = 45;
int sweepAngle = 270;
// Draw arc to screen and save all changes.
graphic.drawArc(new Pen(Color.getBlack()), 0, 0, width, height, startAngle, sweepAngle);
// export image to bmp file format.
image.save(outpath, saveOptions);
}
String dataDir = Utils.getDataDir(DrawingBezier.class) + "DrawingImages/";
// Create an instance of BmpOptions and set its various properties
String outpath = dataDir + "Bezier.bmp";
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.setBitsPerPixel(32);
// Create an instance of Image
try (Image image = new PsdImage(100, 100)) {
// Create and initialize an instance of Graphics class and clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.clear(Color.getYellow());
// Initializes the instance of PEN class with black color and width
Pen BlackPen = new Pen(Color.getBlack(), 3);
float startX = 10;
float startY = 25;
float controlX1 = 20;
float controlY1 = 5;
float controlX2 = 55;
float controlY2 = 10;
float endX = 90;
float endY = 25;
// Draw a Bezier shape by specifying the Pen object having black color and co-ordinate Points and save all changes.
graphic.drawBezier(BlackPen, startX, startY, controlX1, controlY1, controlX2, controlY2, endX, endY);
// export image to bmp file format.
image.save(outpath, saveOptions);
}
String dataDir = Utils.getDataDir(DrawingEllipse.class) + "DrawingImages/";
// Create an instance of BmpOptions and set its various properties
String outpath = dataDir + "Ellipse.bmp";
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.setBitsPerPixel(32);
// Create an instance of Image
try (Image image = new PsdImage(100, 100)) {
// Create and initialize an instance of Graphics class and Clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.clear(Color.getYellow());
// Draw a dotted ellipse shape by specifying the Pen object having red color and a surrounding Rectangle
graphic.drawEllipse(new Pen(Color.getRed()), new Rectangle(30, 10, 40, 80));
// Draw a continuous ellipse shape by specifying the Pen object having solid brush with blue color and a surrounding Rectangle
graphic.drawEllipse(new Pen(new SolidBrush(Color.getBlue())), new Rectangle(10, 30, 80, 40));
// export image to bmp file format.
image.save(outpath, saveOptions);
}
String dataDir = Utils.getDataDir(DrawingLines.class) + "DrawingImages/";
// Create an instance of BmpOptions and set its various properties
String outpath = dataDir + "Lines.bmp";
BmpOptions saveOptions = new BmpOptions();
saveOptions.setBitsPerPixel(32);
// Create an instance of Image
try (Image image = new PsdImage(100, 100)) {
// Create and initialize an instance of Graphics class and Clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.clear(Color.getYellow());
// Draw two dotted diagonal lines by specifying the Pen object having blue color and co-ordinate Points
graphic.drawLine(new Pen(Color.getBlue()), 9, 9, 90, 90);
graphic.drawLine(new Pen(Color.getBlue()), 9, 90, 90, 9);
// Draw a four continuous line by specifying the Pen object having Solid Brush with red color and two point structures
graphic.drawLine(new Pen(new SolidBrush(Color.getRed())), new Point(9, 9), new Point(9, 90));
graphic.drawLine(new Pen(new SolidBrush(Color.getAqua())), new Point(9, 90), new Point(90, 90));
graphic.drawLine(new Pen(new SolidBrush(Color.getBlack())), new Point(90, 90), new Point(90, 9));
graphic.drawLine(new Pen(new SolidBrush(Color.getWhite())), new Point(90, 9), new Point(9, 9));
image.save(outpath, saveOptions);
}
// Create an instance of BmpOptions and set its various properties
String outpath = dataDir + "Rectangle.bmp";
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.setBitsPerPixel(32);
// Create an instance of Image
try (Image image = new PsdImage(100, 100)) {
// Create and initialize an instance of Graphics class, Clear Graphics surface, Draw a rectangle shapes and save all changes.
Graphics graphic = new Graphics(image);
graphic.clear(Color.getYellow());
graphic.drawRectangle(new Pen(Color.getRed()), new Rectangle(30, 10, 40, 80));
graphic.drawRectangle(new Pen(new SolidBrush(Color.getBlue())), new Rectangle(10, 30, 80, 40));
// export image to bmp file format.
image.save(outpath, saveOptions);
}
String dataDir = Utils.getDataDir(DrawingUsingGraphics.class) + "DrawingImages/";
// Create an instance of Image
try (PsdImage image = new PsdImage(500, 500)) {
Graphics graphics = new Graphics(image);
// Clear the image surface with white color and Create and initialize a Pen object with blue color
graphics.clear(Color.getWhite());
Pen pen = new Pen(Color.getBlue());
// Draw Ellipse by defining the bounding rectangle of width 150 and height 100 also Draw a polygon using the LinearGradientBrush
graphics.drawEllipse(pen, new Rectangle(10, 10, 150, 100));
LinearGradientBrush linearGradientBrush = new LinearGradientBrush(image.getBounds(), Color.getRed(), Color.getWhite(), 45f);
// graphics.fillPolygon(linearGradientBrush, new Point(200, 200), new Point(400, 200), new Point(250, 350));
Point[] points = {new Point(200, 200), new Point(400, 200), new Point(250, 350)};
graphics.fillPolygon(linearGradientBrush, points);
// export modified image.
image.save(dataDir + "DrawingUsingGraphics_output.bmp", new BmpOptions());
}
String dataDir = Utils.getDataDir(DrawingUsingGraphicsPath.class) + "DrawingImages/";
// Create an instance of Image and initialize an instance of Graphics
try (PsdImage image = new PsdImage(500, 500)) {
// create graphics surface.
Graphics graphics = new Graphics(image);
graphics.clear(Color.getWhite());
// Create an instance of GraphicsPath and Instance of Figure, add EllipseShape, RectangleShape and TextShape to the figure
GraphicsPath graphicspath = new GraphicsPath();
Figure figure = new Figure();
figure.addShape(new EllipseShape(new RectangleF(0, 0, 499, 499)));
figure.addShape(new RectangleShape(new RectangleF(0, 0, 499, 499)));
figure.addShape(new TextShape("Aspose.PSD", new RectangleF(170, 225, 170, 100), new Font("Arial", 20), StringFormat.getGenericTypographic()));
Figure[] fig = {figure};
graphicspath.addFigures(fig);
graphics.drawPath(new Pen(Color.getBlue()), graphicspath);
// Create an instance of HatchBrush and set its properties also Fill path by supplying the brush and GraphicsPath objects
HatchBrush hatchbrush = new HatchBrush();
hatchbrush.setBackgroundColor(Color.getBrown());
hatchbrush.setForegroundColor(Color.getBlue());
hatchbrush.setHatchStyle(HatchStyle.Vertical);
graphics.fillPath(hatchbrush, graphicspath);
image.save(dataDir + "DrawingUsingGraphicsPath_output.psd");
}
// Create an instance of PSD Metered class
Metered metered = new Metered();
// Access the setMeteredKey property and pass public and private keys as parameters
metered.setMeteredKey("*****", "*****");
// Get metered data amount before calling API
System.out.println("Amount Consumed Before: " + Metered.getConsumptionQuantity());
// Get metered data amount After calling API
System.out.println("Amount Consumed After: " + Metered.getConsumptionQuantity());
String dataDir = Utils.getDataDir(AIToGIF.class) + "AI/";
String sourceFileName = dataDir + "34992OStroke.ai";
String outFileName = dataDir + "34992OStroke.gif";
try (AiImage image = (AiImage) Image.load(sourceFileName)) {
GifOptions options = new GifOptions();
options.setDoPaletteCorrection(false);
image.save(outFileName, options);
}
String dataDir = Utils.getDataDir(AIToJPG.class) + "AI/";
String sourceFileName = dataDir + "34992OStroke.ai";
String outFileName = dataDir + "34992OStroke.jpg";
try (AiImage image = (AiImage)Image.load(sourceFileName)) {
JpegOptions options = new JpegOptions();
options.setQuality(85);
image.save(outFileName, options);
}
String dataDir = Utils.getDataDir(AIToPDF.class) + "AI/";
String sourceFileName = dataDir + "34992OStroke.ai";
String outFileName = dataDir + "34992OStroke.pdf";
try (AiImage image = (AiImage) Image.load(sourceFileName)) {
PdfOptions options = new PdfOptions();
image.save(outFileName, options);
}
String dataDir = Utils.getDataDir(AIToPNG.class) + "AI/";
String sourceFileName = dataDir + "34992OStroke.ai";
String outFileName = dataDir + "34992OStroke.png";
try (AiImage image = (AiImage) Image.load(sourceFileName)) {
PngOptions options = new PngOptions();
options.setColorType(PngColorType.TruecolorWithAlpha);
image.save(outFileName, options);
}
String dataDir = Utils.getDataDir(AIToPSD.class) + "AI/";
String sourceFileName = dataDir + "34992OStroke.ai";
String outFileName = dataDir + "34992OStroke.psd";
try (AiImage image = (AiImage) Image.load(sourceFileName)) {
PsdOptions options = new PsdOptions();
image.save(outFileName, options);
}
String dataDir = Utils.getDataDir(AIToPSD.class) + "AI/";
String sourceFileName = dataDir + "34992OStroke.ai";
String outFileName = dataDir + "34992OStroke.tiff";
try (AiImage image = (AiImage) Image.load(sourceFileName)) {
image.save(outFileName, new TiffOptions(TiffExpectedFormat.TiffDeflateRgba));
}
String dataDir = Utils.getDataDir(AddThumbnailToEXIFSegment.class) + "ModifyingAndConvertingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "1280px-Zebras_Serengeti.psd")) {
// Iterate over resources.
for (int i = 0; i < image.getImageResources().length; i++) {
// Find thumbnail resource. Typically they are in the Jpeg file format.
if (image.getImageResources()[i] instanceof ThumbnailResource || image.getImageResources()[i] instanceof Thumbnail4Resource) {
// Adjust thumbnail data.
ThumbnailResource thumbnail = (ThumbnailResource) image.getImageResources()[i];
JpegExifData exifData = new JpegExifData();
PsdImage thumbnailImage = new PsdImage(100, 100);
try {
// Fill thumbnail data.
int[] pixels = new int[thumbnailImage.getWidth() * thumbnailImage.getHeight()];
for (int j = 0; j < pixels.length; j++) {
pixels[j] = j;
}
// Assign thumbnail data.
thumbnailImage.saveArgb32Pixels(thumbnailImage.getBounds(), pixels);
exifData.setThumbnail(thumbnailImage);
thumbnail.getJpegOptions().setExifData(exifData);
} catch (Exception e) {
thumbnailImage.dispose();
}
}
}
image.save();
}
String dataDir = Utils.getDataDir(AddThumbnailToJFIFSegment.class) + "ModifyingAndConvertingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "1280px-Zebras_Serengeti.psd")) {
// Iterate over resources.
for (int i = 0; i < image.getImageResources().length; i++) {
// Find thumbnail resource. Typically they are in the Jpeg file format.
if (image.getImageResources()[i] instanceof ThumbnailResource || image.getImageResources()[i] instanceof Thumbnail4Resource) {
// Adjust thumbnail data.
ThumbnailResource thumbnail = (ThumbnailResource) image.getImageResources()[i];
JpegExifData exifData = new JpegExifData();
PsdImage thumbnailImage = new PsdImage(100, 100);
try {
// Fill thumbnail data.
int[] pixels = new int[thumbnailImage.getWidth() * thumbnailImage.getHeight()];
for (int j = 0; j < pixels.length; j++) {
pixels[j] = j;
}
// Assign thumbnail data.
thumbnailImage.saveArgb32Pixels(thumbnailImage.getBounds(), pixels);
exifData.setThumbnail(thumbnailImage);
thumbnail.getJpegOptions().setExifData(exifData);
} catch (Exception e) {
thumbnailImage.dispose();
}
}
}
image.save();
}
String dataDir = Utils.getDataDir(AutoCorrectOrientationOfJPEGImages.class) + "ModifyingAndConvertingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "1280px-Zebras_Serengeti.psd")) {
// Iterate over resources.
for (int i = 0; i < image.getImageResources().length; i++) {
// Find thumbnail resource. Typically they are in the Jpeg file format.
if (image.getImageResources()[i] instanceof ThumbnailResource || image.getImageResources()[i] instanceof Thumbnail4Resource) {
// Adjust thumbnail data.
ThumbnailResource thumbnail = (ThumbnailResource) image.getImageResources()[i];
JpegExifData exifData = thumbnail.getJpegOptions().getExifData();
if (exifData != null && exifData.getThumbnail() != null) {
// If there is thumbnail stored then auto-rotate it.
JpegImage jpegImage = (JpegImage) exifData.getThumbnail();
if (jpegImage != null) {
jpegImage.autoRotate();
}
}
}
}
// Save image.
image.save();
}
String dataDir = Utils.getDataDir(ColorTypeAndCompressionType.class) + "ModifyingAndConvertingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "PsdImage.psd")) {
JpegOptions options = new JpegOptions();
options.setColorType(JpegCompressionColorMode.Grayscale);
options.setCompressionType(JpegCompressionMode.Progressive);
image.save(dataDir + "ColorTypeAndCompressionType_output.jpg", options);
}
String dataDir = Utils.getDataDir(ExtractThumbnailFromJFIF.class) + "ModifyingAndConvertingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "1280px-Zebras_Serengeti.psd")) {
// Iterate over resources.
for (int i = 0; i < image.getImageResources().length; i++) {
// Find thumbnail resource. Typically they are in the Jpeg file format.
if (image.getImageResources()[i] instanceof ThumbnailResource || image.getImageResources()[i] instanceof Thumbnail4Resource) {
// Extract thumbnail data and store it as a separate image file.
ThumbnailResource thumbnail = (ThumbnailResource) image.getImageResources()[i];
JFIFData jfif = thumbnail.getJpegOptions().getJfif();
if (jfif != null) {
// extract JFIF data and process.
}
JpegExifData exif = thumbnail.getJpegOptions().getExifData();
if (exif != null) {
// extract Exif data and process.
}
}
}
}
String dataDir = Utils.getDataDir(ExtractThumbnailFromPSD.class) + "ModifyingAndConvertingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "1280px-Zebras_Serengeti.psd")) {
// Iterate over resources.
for (int i = 0; i < image.getImageResources().length; i++) {
// Find thumbnail resource. Typically they are in the Jpeg file format.
if (image.getImageResources()[i] instanceof ThumbnailResource || image.getImageResources()[i] instanceof Thumbnail4Resource) {
// Extract thumbnail data and store it as a separate image file.
ThumbnailResource thumbnail = (ThumbnailResource) image.getImageResources()[i];
int[] data = ((ThumbnailResource) image.getImageResources()[i]).getThumbnailArgb32Data();
try (PsdImage extractedThumnailImage = new PsdImage(thumbnail.getWidth(), thumbnail.getHeight())) {
extractedThumnailImage.saveArgb32Pixels(extractedThumnailImage.getBounds(), data);
extractedThumnailImage.save(dataDir + "extracted_thumbnail.jpg", new JpegOptions());
}
}
}
}
String dataDir = Utils.getDataDir(ReadAllEXIFTagList.class) + "ModifyingAndConvertingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "1280px-Zebras_Serengeti.psd")) {
// Iterate over resources.
for (int i = 0; i < image.getImageResources().length; i++) {
// Find thumbnail resource. Typically they are in the Jpeg file format.
if (image.getImageResources()[i] instanceof ThumbnailResource || image.getImageResources()[i] instanceof Thumbnail4Resource) {
// Extract thumbnail data and store it as a separate image file.
ThumbnailResource thumbnail = (ThumbnailResource) image.getImageResources()[i];
JpegExifData exifData = thumbnail.getJpegOptions().getExifData();
if (exifData != null) {
for (int j = 0; j < exifData.getProperties().length; j++) {
System.out.println(exifData.getProperties()[j].getId() + ":" + exifData.getProperties()[j].getValue());
}
}
}
}
}
String dataDir = Utils.getDataDir(ReadAllEXIFTags.class) + "ModifyingAndConvertingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "1280px-Zebras_Serengeti.psd")) {
// Iterate over resources.
for (int i = 0; i < image.getImageResources().length; i++) {
// Find thumbnail resource. Typically they are in the Jpeg file format.
if (image.getImageResources()[i] instanceof ThumbnailResource || image.getImageResources()[i] instanceof Thumbnail4Resource) {
// Extract exif data and print to the console.
ThumbnailResource thumbnail = (ThumbnailResource) image.getImageResources()[i];
JpegExifData exif = thumbnail.getJpegOptions().getExifData();
if (exif != null) {
for (int j = 0; j < exif.getProperties().length; j++) {
System.out.println(exif.getProperties()[j].getId() + ":" + exif.getProperties()[j].getValue());
}
}
}
}
}
String dataDir = Utils.getDataDir(ReadandModifyJpegEXIFTags.class) + "ModifyingAndConvertingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "1280px-Zebras_Serengeti.psd")) {
// Iterate over resources.
for (int i = 0; i < image.getImageResources().length; i++) {
// Find thumbnail resource. Typically they are in the Jpeg file format.
if (image.getImageResources()[i] instanceof ThumbnailResource || image.getImageResources()[i] instanceof Thumbnail4Resource) {
// Extract thumbnail data and store it as a separate image file.
ThumbnailResource thumbnail = (ThumbnailResource) image.getImageResources()[i];
JpegExifData exifData = thumbnail.getJpegOptions().getExifData();
if (exifData != null) {
// extract Exif data and process.
System.out.println("Camera Owner Name: " + exifData.getCameraOwnerName());
System.out.println("Aperture Value: " + exifData.getApertureValue());
System.out.println("Orientation: " + exifData.getOrientation());
System.out.println("Focal Length: " + exifData.getFocalLength());
System.out.println("Compression: " + exifData.getCompression());
}
}
}
}
String dataDir = Utils.getDataDir(ReadSpecificEXIFTagsInformation.class) + "ModifyingAndConvertingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "1280px-Zebras_Serengeti.psd")) {
// Iterate over resources.
for (int i = 0; i < image.getImageResources().length; i++) {
// Find thumbnail resource. Typically they are in the Jpeg file format.
if (image.getImageResources()[i] instanceof ThumbnailResource || image.getImageResources()[i] instanceof Thumbnail4Resource) {
// Extract exif data and print to the console.
JpegExifData exif = ((ThumbnailResource) image.getImageResources()[i]).getJpegOptions().getExifData();
if (exif != null) {
System.out.println("Exif WhiteBalance: " + exif.getWhiteBalance());
System.out.println("Exif PixelXDimension: " + exif.getPixelXDimension());
System.out.println("Exif PixelYDimension: " + exif.getPixelYDimension());
System.out.println("Exif ISOSpeed: " + exif.getISOSpeed());
System.out.println("Exif FocalLength: " + exif.getFocalLength());
}
}
}
}
String dataDir = Utils.getDataDir(SupportFor2And7BitsJPEG.class) + "ModifyingAndConvertingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "PsdImage.psd")) {
JpegOptions options = new JpegOptions();
// Set 2 bits per sample to see the difference in size and quality
byte bpp = 2;
//Just replace one line given below in examples to use YCCK instead of CMYK
//options.ColorType = JpegCompressionColorMode.Cmyk;
options.setColorType(JpegCompressionColorMode.Cmyk);
options.setCompressionType(JpegCompressionMode.JpegLs);
options.setBitsPerChannel(bpp);
// The default profiles will be used.
options.setRgbColorProfile(null);
options.setCmykColorProfile(null);
image.save(dataDir + "2_7BitsJPEG_output.jpg", options);
}
String dataDir = Utils.getDataDir(SupportForJPEGLSWithCMYK.class) + "ModifyingAndConvertingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "PsdImage.psd")) {
JpegOptions options = new JpegOptions();
//Just replace one line given below in examples to use YCCK instead of CMYK
//options.ColorType = JpegCompressionColorMode.Cmyk;
options.setColorType(JpegCompressionColorMode.Cmyk);
options.setCompressionType(JpegCompressionMode.JpegLs);
// The default profiles will be used.
options.setRgbColorProfile(null);
options.setCmykColorProfile(null);
image.save(dataDir + "output.jpg", options);
}
try (PsdImage image1 = (PsdImage) Image.load(dataDir + "PsdImage.psd")) {
JpegOptions options1 = new JpegOptions();
//Just replace one line given below in examples to use YCCK instead of CMYK
//options.ColorType = JpegCompressionColorMode.Cmyk;
options1.setColorType(JpegCompressionColorMode.Cmyk);
options1.setCompressionType(JpegCompressionMode.Lossless);
// The default profiles will be used.
options1.setRgbColorProfile(null);
options1.setCmykColorProfile(null);
image1.save(dataDir + "output2.jpg", options1);
}
String dataDir = Utils.getDataDir(WritingAndModifyingEXIFData.class) + "ModifyingAndConvertingImages/";
try (PsdImage image = (PsdImage) Image.load(dataDir + "1280px-Zebras_Serengeti.psd")) {
// Iterate over resources.
for (int i = 0; i < image.getImageResources().length; i++) {
// Find thumbnail resource. Typically they are in the Jpeg file format.
if (image.getImageResources()[i] instanceof ThumbnailResource || image.getImageResources()[i] instanceof Thumbnail4Resource) {
// Extract exif data and print to the console.
JpegExifData exif = ((ThumbnailResource) image.getImageResources()[i]).getJpegOptions().getExifData();
if (exif != null) {
// Set LensMake, WhiteBalance, Flash information Save the image
exif.setLensMake("Sony");
exif.setWhiteBalance(ExifWhiteBalance.Auto);
exif.setFlash(ExifFlash.Fired);
}
}
}
image.save(dataDir + "aspose_out.psd");
}
String dataDir = Utils.getDataDir(ApplyFilterMethod.class) + "ModifyingAndConvertingImages/";
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "sample.psd")) {
// Create an instance of PngOptions, Set the PNG filter method and Save changes to the disc
PngOptions options = new PngOptions();
options.setFilterType(PngFilterType.Paeth);
psdImage.save(dataDir + "ApplyFilterMethod_out.png", options);
}
String dataDir = Utils.getDataDir(ChangeBackgroundColor.class) + "ModifyingAndConvertingImages/";
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "sample.psd");
// Convert to PngImage based on PsdImage.
PsdImage pngImage = new PsdImage(psdImage)) {
int[] pixels = pngImage.loadArgb32Pixels(pngImage.getBounds());
// Iterate through the pixel array and Check the pixel information
//that if it is a transparent color pixel and Change the pixel color to white
int transparent = pngImage.getTransparentColor().toArgb();
int replacementColor = Color.getYellow().toArgb();
for (int i = 0; i < pixels.length; i++) {
if (pixels[i] == transparent) {
pixels[i] = replacementColor;
}
}
// Replace the pixel array into the image.
pngImage.saveArgb32Pixels(pngImage.getBounds(), pixels);
pngImage.save(dataDir + "ChangeBackground_out.png");
}
String dataDir = Utils.getDataDir(ApplyFilterMethod.class) + "ModifyingAndConvertingImages/";
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "sample.psd")) {
// Loop over possible CompressionLevel range
for (int i = 0; i <= 9; i++) {
// Create an instance of PngOptions for each resultant PNG, Set CompressionLevel and Save result on disk
PngOptions options = new PngOptions();
options.setCompressionLevel(i);
psdImage.save(dataDir + i + "_out.png", options);
}
}
String dataDir = Utils.getDataDir(SettingResolution.class) + "ModifyingAndConvertingImages/";
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "sample.psd")) {
// Create an instance of PngOptions, Set the horizontal & vertical resolutions and Save the result on disc
PngOptions options = new PngOptions();
options.setResolutionSettings(new ResolutionSetting(72, 96));
psdImage.save(dataDir + "SettingResolution_output.png", options);
}
String dataDir = Utils.getDataDir(SpecifyBitDepth.class) + "ModifyingAndConvertingImages/";
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "sample.psd")) {
// Create an instance of PngOptions, Set the desired ColorType, BitDepth according to the specified ColorType and save image
PngOptions options = new PngOptions();
options.setColorType(PngColorType.Grayscale);
options.setBitDepth((byte) 1);
psdImage.save(dataDir + "SpecifyBitDepth_out.png", options);
}
String dataDir = Utils.getDataDir(SpecifyTransparency.class) + "ModifyingAndConvertingImages/";
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "sample.psd");
// Initialize PNG image with psd image pixel data.
PsdImage pngImage = new PsdImage(psdImage)) {
// specify the PNG image transparency options and save to file.
pngImage.setTransparentColor(Color.getWhite());
pngImage.setTransparentColor(true);
pngImage.save(dataDir + "Specify_Transparency_result.png");
}
String dataDir = Utils.getDataDir(PSBToJPG.class) + "PSB/";
String sourceFileName = dataDir + "Simple.psb";
PsdLoadOptions options = new PsdLoadOptions();
try (PsdImage image = (PsdImage) Image.load(sourceFileName, options)) {
JpegOptions jpgoptions = new JpegOptions();
jpgoptions.setQuality(95);
// All jpeg and psd files must be readable
image.save(dataDir + "Simple_output.jpg", jpgoptions);
image.save(dataDir + "Simple_output.psb");
}
String dataDir = Utils.getDataDir(PSBToPDF.class) + "PSB/";
String sourceFileName = dataDir + "Simple.psb";
try (PsdImage image = (PsdImage) Image.load(sourceFileName)) {
image.save(dataDir + "Simple_output.pdf", new PdfOptions());
}
String dataDir = Utils.getDataDir(PSBToPSD.class) + "PSB/";
String sourceFileName = dataDir + "2layers.psb";
try (PsdImage image = (PsdImage) Image.load(sourceFileName)) {
PsdOptions options = new PsdOptions();
options.setFileFormatVersion(FileFormatVersion.Psd);
image.save(dataDir + "ConvertFromPsb_out.psd", options);
}
String dataDir = Utils.getDataDir(AddChannelMixerAdjustmentLayer.class) + "PSD/";
String sourceFileName = dataDir + "ChannelMixerAdjustmentLayerRgb.psd";
String psdPathAfterChange = dataDir + "ChannelMixerAdjustmentLayerRgbChanged.psd";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < im.getLayers().length; i++) {
if (im.getLayers()[i] instanceof RgbChannelMixerLayer) {
RgbChannelMixerLayer rgbLayer = (RgbChannelMixerLayer) im.getLayers()[i];
rgbLayer.getRedChannel().setBlue((short) 100);
rgbLayer.getBlueChannel().setGreen((short) -100);
rgbLayer.getGreenChannel().setConstant((short) 50);
}
}
im.save(psdPathAfterChange);
}
// Cmyk Channel Mixer
sourceFileName = dataDir + "ChannelMixerAdjustmentLayerCmyk.psd";
psdPathAfterChange = dataDir + "ChannelMixerAdjustmentLayerCmykChanged.psd";
try (PsdImage img = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < img.getLayers().length; i++) {
if (img.getLayers()[i] instanceof CmykChannelMixerLayer) {
CmykChannelMixerLayer cmykLayer = (CmykChannelMixerLayer) img.getLayers()[i];
cmykLayer.getCyanChannel().setBlack((short) 20);
cmykLayer.getMagentaChannel().setYellow((short) 50);
cmykLayer.getYellowChannel().setCyan((short) -25);
cmykLayer.getBlackChannel().setYellow((short) 25);
}
}
img.save(psdPathAfterChange);
}
// Adding the new layer(Cmyk for this example)
sourceFileName = dataDir + "CmykWithAlpha.psd";
psdPathAfterChange = dataDir + "ChannelMixerAdjustmentLayerCmykChanged.psd";
try (PsdImage img1 = (PsdImage) Image.load(sourceFileName)) {
ChannelMixerLayer newlayer = img1.addChannelMixerAdjustmentLayer();
newlayer.getChannelByIndex(2).setConstant((short) 50);
newlayer.getChannelByIndex(0).setConstant((short) 50);
img1.save(psdPathAfterChange);
}
String dataDir = Utils.getDataDir(AddCurvesAdjustmentLayer.class) + "PSD/";
// Curves layer editing
String sourceFileName = dataDir + "CurvesAdjustmentLayer";
String psdPathAfterChange = dataDir + "CurvesAdjustmentLayerChanged";
for (int j = 1; j < 2; j++) {
String fileName = sourceFileName + ".psd";
try (PsdImage im = (PsdImage) Image.load(fileName)) {
for (int k = 0; k < im.getLayers().length; k++) {
if (im.getLayers()[k] instanceof CurvesLayer) {
CurvesLayer curvesLayer = (CurvesLayer) im.getLayers()[k];
if (curvesLayer.isDiscreteManagerUsed()) {
CurvesDiscreteManager manager = (CurvesDiscreteManager) curvesLayer.getCurvesManager();
for (int i = 10; i < 50; i++) {
manager.setValueInPosition(0, (byte) i, (byte) (15 + (i * 2)));
}
} else {
CurvesContinuousManager manager = (CurvesContinuousManager) curvesLayer.getCurvesManager();
manager.addCurvePoint((byte) 0, (byte) 50, (byte) 100);
manager.addCurvePoint((byte) 0, (byte) 150, (byte) 130);
}
}
}
// Save PSD
im.save(psdPathAfterChange + Integer.toString(j) + ".psd");
}
String dataDir = Utils.getDataDir(AddDiagnolWatermark.class) + "PSD/";
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "layers.psd")) {
// Create graphics object to perform draw operations.
Graphics graphics = new Graphics(psdImage);
// Create font to draw watermark with.
Font font = new Font("Arial", 20.0f);
// Create a solid brush with color alpha set near to 0 to use watermarking effect.
SolidBrush brush = new SolidBrush(Color.fromArgb(50, 128, 128, 128));
// specify transform matrix to rotate watermark.
graphics.setTransform(new Matrix());
graphics.getTransform().rotateAt(45, new PointF(psdImage.getWidth() / 2, psdImage.getHeight() / 2));
// Specify string alignment to put watermark at the image center.
StringFormat sf = new StringFormat();
sf.setAlignment(StringAlignment.Center);
// Draw watermark using font, partly-transparent brush at the image center.
graphics.drawString("Some watermark text", font, brush, new RectangleF(0, psdImage.getHeight() / 2, psdImage.getWidth(), psdImage.getHeight() / 2), sf);
// Export the image into PNG file format.
psdImage.save(dataDir + "AddDiagnolWatermark_output.png", new PngOptions());
}
String dataDir = Utils.getDataDir(AddHueSaturationAdjustmentLayer.class) + "PSD/";
// Hue/Saturation layer editing
String sourceFileName = dataDir + "HueSaturationAdjustmentLayer.psd";
String psdPathAfterChange = dataDir + "HueSaturationAdjustmentLayerChanged.psd";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < im.getLayers().length; i++) {
if (im.getLayers()[i] instanceof HueSaturationLayer) {
HueSaturationLayer hueLayer = (HueSaturationLayer) im.getLayers()[i];
hueLayer.setHue((short) -25);
hueLayer.setSaturation((short) -12);
hueLayer.setLightness((short) 67);
ColorRangeHsl colorRange = hueLayer.getRange(2);
colorRange.setHue((short) -40);
colorRange.setSaturation((short) 50);
colorRange.setLightness((short) -20);
colorRange.setMostLeftBorder((short) 300);
}
}
im.save(psdPathAfterChange);
}
// Hue/Saturation layer adding
sourceFileName = dataDir + "PhotoExample.psd";
psdPathAfterChange = dataDir + "PhotoExampleAddedHueSaturation.psd";
try (PsdImage img = (PsdImage) Image.load(sourceFileName)) {
//this.SaveForVisualTest(im, this.OutputPath, prefix + file, "before");
HueSaturationLayer hueLayer = img.addHueSaturationAdjustmentLayer();
hueLayer.setHue((short) -25);
hueLayer.setSaturation((short) -12);
hueLayer.setLightness((short) 67);
ColorRangeHsl colorRange = hueLayer.getRange(2);
colorRange.setHue((short) -160);
colorRange.setSaturation((short) 100);
colorRange.setLightness((short) 20);
colorRange.setMostLeftBorder((short) 300);
img.save(psdPathAfterChange);
}
String dataDir = Utils.getDataDir(AddIopaResource.class) + "PSD/";
String sourceFileName = dataDir + "FillOpacitySample.psd";
String exportPath = dataDir + "FillOpacitySampleChanged.psd";
try (PsdImage im = (PsdImage) (Image.load(sourceFileName))) {
Layer layer = im.getLayers()[2];
LayerResource[] resources = layer.getResources();
for (int i = 0; i < resources.length; i++) {
if (resources[i] instanceof IopaResource) {
IopaResource iopaResource = (IopaResource) resources[i];
iopaResource.setFillOpacity((byte) 200);
}
}
im.save(exportPath);
}
String dataDir = Utils.getDataDir(AddLevelAdjustmentLayer.class) + "PSD/";
String sourceFileName = dataDir + "LevelsAdjustmentLayer.psd";
String psdPathAfterChange = dataDir + "LevelsAdjustmentLayerChanged.psd";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < im.getLayers().length; i++) {
if (im.getLayers()[i] instanceof LevelsLayer) {
LevelsLayer levelsLayer = (LevelsLayer) im.getLayers()[i];
LevelChannel channel = levelsLayer.getChannel(0);
channel.setInputMidtoneLevel(2.0f);
channel.setInputShadowLevel((short) 10);
channel.setInputHighlightLevel((short) 230);
channel.setOutputShadowLevel((short) 20);
channel.setOutputHighlightLevel((short) 200);
}
}
// Save PSD
im.save(psdPathAfterChange);
}
String dataDir = Utils.getDataDir(AddTextLayerOnRuntime.class) + "PSD/";
String sourceFileName = dataDir + "OneLayer.psd";
String psdPath = dataDir + "ImageWithTextLayer.psd";
try (Image img = Image.load(sourceFileName)) {
PsdImage im = (PsdImage) img;
Rectangle rect = new Rectangle(
(int) (im.getWidth() * 0.25),
(int) (im.getHeight() * 0.25),
(int) (im.getWidth() * 0.5),
(int) (im.getHeight() * 0.5));
TextLayer layer = im.addTextLayer("Added text", rect);
im.save(psdPath);
}
String dataDir = Utils.getDataDir(AddWatermark.class) + "PSD/";
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "layers.psd")) {
// Create graphics object to perform draw operations.
Graphics graphics = new Graphics(psdImage);
// Create font to draw watermark with.
Font font = new Font("Arial", 20.0f);
// Create a solid brush with color alpha set near to 0 to use watermarking effect.
SolidBrush brush = new SolidBrush(Color.fromArgb(50, 128, 128, 128));
// Specify string alignment to put watermark at the image center.
StringFormat sf = new StringFormat();
sf.setAlignment(StringAlignment.Center);
sf.setLineAlignment(StringAlignment.Center);
// Draw watermark using font, partly-transparent brush and rotation matrix at the image center.
graphics.drawString("Some watermark text", font, brush, new RectangleF(0, 0, psdImage.getWidth(), psdImage.getHeight()), sf);
// Export the image into PNG file format.
psdImage.save(dataDir + "AddWatermark_output.png", new PngOptions());
}
String dataDir = Utils.getDataDir(ColorFillLayer.class) + "PSD/";
String sourceFileName = dataDir + "ColorFillLayer.psd";
String exportPath = dataDir + "ColorFillLayer_output.psd";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < im.getLayers().length; i++) {
if (im.getLayers()[i] instanceof FillLayer) {
FillLayer fillLayer = (FillLayer) im.getLayers()[i];
if (fillLayer.getFillSettings().getFillType() != FillType.Color) {
throw new Exception("Wrong Fill Layer");
}
IColorFillSettings settings = (IColorFillSettings) fillLayer.getFillSettings();
settings.setColor(Color.getRed());
fillLayer.update();
im.save(exportPath);
break;
}
}
}
String dataDir = Utils.getDataDir(ColorReplacementInPSD.class) + "PSD/";
// Load a PSD file as an image and caste it into PsdImage
try (PsdImage image = (PsdImage) Image.load(dataDir + "sample.psd")) {
for (int i = 0; i < image.getLayers().length; i++) {
if (image.getLayers()[i].getName() == "Rectangle 1") {
Layer layer = image.getLayers()[i];
int dd = 0;
layer.hasBackgroundColor();
layer.setBackgroundColor(Color.getOrange());
}
}
image.save(dataDir + "asposeImage02.psd");
}
String dataDir = Utils.getDataDir(ControllCacheReallocation.class) + "PSD/";
// By default the cache folder is set to the local temp directory. You can specify a different cache folder from the default this way:
Cache.setCacheFolder(dataDir);
// Set cache on disk.
Cache.setCacheType(CacheType.CacheOnDiskOnly);
// The default cache max value is 0, which means that there is no upper limit
Cache.setMaxDiskSpaceForCache(1073741824); // 1 gigabyte
Cache.setMaxMemoryForCache(1073741824); // 1 gigabyte
// We do not recommend that you change the following property because it may greatly affect performance
Cache.setExactReallocateOnly(false);
// At any time you can check how many bytes are currently allocated for the cache in memory or on disk By examining the following properties
long l1 = Cache.getAllocatedDiskBytesCount();
long l2 = Cache.getAllocatedMemoryBytesCount();
PsdOptions options = new PsdOptions();
Color[] color = {Color.getRed(), Color.getBlue(), Color.getBlack(), Color.getWhite()};
options.setPalette(new ColorPalette(color));
options.setSource(new StreamSource(new java.io.ByteArrayInputStream(new byte[0])));
try (RasterImage image = (RasterImage) Image.create(options, 100, 100)) {
Color[] pixels = new Color[10000];
for (int i = 0; i < pixels.length; i++) {
pixels[i] = Color.getWhite();
}
image.savePixels(image.getBounds(), pixels);
// After executing the code above 40000 bytes are allocated to disk.
long diskBytes = Cache.getAllocatedDiskBytesCount();
long memoryBytes = Cache.getAllocatedMemoryBytesCount();
// The allocation properties may be used to check whether all Aspose.PSD objects were properly disposed. If you've forgotten to call dispose on an object the cache values will not be 0.
l1 = Cache.getAllocatedDiskBytesCount();
l2 = Cache.getAllocatedMemoryBytesCount();
}
String dataDir = Utils.getDataDir(CreateIndexedPSDFiles.class) + "PSD/";
// Create an instance of PsdOptions and set it's properties
PsdOptions createOptions = new PsdOptions();
createOptions.setSource(new FileCreateSource(dataDir + "Newsample_out.psd", false));
createOptions.setColorMode(ColorModes.Indexed);
createOptions.setVersion(5);
// Create a new color palette having RGB colors, Set Palette property & compression method
Color[] palette = {Color.getRed(), Color.getGreen(), Color.getBlue(), Color.getYellow()};
createOptions.setPalette(new PsdColorPalette(palette));
createOptions.setCompressionMethod(CompressionMethod.RLE);
// Create a new PSD with PsdOptions created previously
try (Image psd = Image.create(createOptions, 500, 500)) {
// Draw some graphics over the newly created PSD
Graphics graphics = new Graphics(psd);
graphics.clear(Color.getWhite());
graphics.drawEllipse(new Pen(Color.getRed(), 6), new Rectangle(0, 0, 400, 400));
psd.save();
}
String dataDir = Utils.getDataDir(CreateThumbnailsFromPSDFiles.class) + "PSD/";
// Load a PSD file as an image and caste it into PsdImage
try (PsdImage image = (PsdImage) Image.load(dataDir + "sample.psd")) {
int index = 0;
// Iterate over the PSD resources
for (int i = 0; i < image.getImageResources().length; i++) {
index++;
// Check if the resource is of thumbnail type
if (image.getImageResources()[i] instanceof ThumbnailResource) {
// Retrieve the ThumbnailResource and Check the format of the ThumbnailResource
ThumbnailResource thumbnail = (ThumbnailResource) image.getImageResources()[i];
if (thumbnail.getFormat() == ThumbnailFormat.KJpegRgb) {
// Create a new BmpImage by specifying the width and height, Store the pixels of thumbnail on to the newly created BmpImage and save image
PsdImage thumnailImage = new PsdImage(thumbnail.getWidth(), thumbnail.getHeight());
thumnailImage.savePixels(thumnailImage.getBounds(), thumbnail.getThumbnailData());
thumnailImage.save(dataDir + "CreateThumbnailsFromPSDFiles_out_" + i + ".bmp");
}
}
}
}
String dataDir = Utils.getDataDir(DetectFlattenedPSD.class) + "PSD/";
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "layers.psd")) {
// Do processing, Get the true value if PSD is flatten and false in case the PSD is not flatten.
System.out.println(psdImage.isFlatten());
}
String dataDir = Utils.getDataDir(ExportImageToPSD.class) + "PSD/";
// Create a new image from scratch.
try (PsdImage bmpImage = new PsdImage(300, 300)) {
// Fill image data.
Graphics graphics = new Graphics(bmpImage);
graphics.clear(Color.getWhite());
Pen pen = new Pen(Color.getBrown());
graphics.drawRectangle(pen, bmpImage.getBounds());
// Create an instance of PsdOptions, Set it's various properties Save image to disk in PSD format
PsdOptions psdOptions = new PsdOptions();
psdOptions.setColorMode(ColorModes.Rgb);
psdOptions.setCompressionMethod(CompressionMethod.Raw);
psdOptions.setVersion(4);
bmpImage.save(dataDir + "ExportImageToPSD_output.psd", psdOptions);
}
String dataDir = Utils.getDataDir(ExportPSDLayerToRasterImage.class) + "PSD/";
// Load a PSD file as an image and caste it into PsdImage
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "sample.psd")) {
// Create an instance of PngOptions class
PngOptions pngOptions = new PngOptions();
pngOptions.setColorType(PngColorType.TruecolorWithAlpha);
// Loop through the list of layers
for (int i = 0; i < psdImage.getLayers().length; i++) {
// Convert and save the layer to PNG file format.
psdImage.getLayers()[i].save(String.format("layer_out{0}.png", i + 1), pngOptions);
}
}
String dataDir = Utils.getDataDir(FillOpacityOfLayers.class) + "PSD/";
// Change the Fill Opacity property
String sourceFileName = dataDir + "FillOpacitySample.psd";
String exportPath = dataDir + "FillOpacitySampleChanged.psd";
try (PsdImage im = (PsdImage) (Image.load(sourceFileName))) {
Layer layer = im.getLayers()[2];
layer.setFillOpacity(5);
im.save(exportPath);
}
String dataDir = Utils.getDataDir(GradientFillLayer.class) + "PSD/";
String sourceFileName = dataDir + "ComplexGradientFillLayer.psd";
String outputFile = dataDir + "ComplexGradientFillLayer_output.psd";
try (PsdImage image = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < image.getLayers().length; i++) {
if (image.getLayers()[i] instanceof FillLayer) {
FillLayer fillLayer = (FillLayer) image.getLayers()[i];
if (fillLayer.getFillSettings().getFillType() != FillType.Gradient) {
throw new Exception("Wrong Fill Layer");
}
IGradientFillSettings settings = (IGradientFillSettings) fillLayer.getFillSettings();
if (
Math.abs(settings.getAngle() - 45) > 0.25 ||
settings.getDither() != true ||
settings.getAlignWithLayer() != false ||
settings.getReverse() != false ||
Math.abs(settings.getHorizontalOffset() - (-39)) > 0.25 ||
Math.abs(settings.getVerticalOffset() - (-5)) > 0.25 ||
settings.getTransparencyPoints().length != 3 ||
settings.getColorPoints().length != 2 ||
Math.abs(100.0 - settings.getTransparencyPoints()[0].getOpacity()) > 0.25 ||
settings.getTransparencyPoints()[0].getLocation() != 0 ||
settings.getTransparencyPoints()[0].getMedianPointLocation() != 50 ||
settings.getColorPoints()[0].getColor() != Color.fromArgb(203, 64, 140) ||
settings.getColorPoints()[0].getLocation() != 0 ||
settings.getColorPoints()[0].getMedianPointLocation() != 50) {
throw new Exception("Gradient Fill was not read correctly");
}
settings.setAngle(0.0);
settings.setDither(false);
settings.setAlignWithLayer(true);
settings.setReverse(true);
settings.setHorizontalOffset(25);
settings.setVerticalOffset(-15);
List<IGradientColorPoint> colorPoints = new ArrayList<IGradientColorPoint>();
Collections.addAll(colorPoints, settings.getColorPoints());
List<IGradientTransparencyPoint> transparencyPoints = new ArrayList<IGradientTransparencyPoint>();
Collections.addAll(transparencyPoints, settings.getTransparencyPoints());
GradientColorPoint gr1 = new GradientColorPoint();
gr1.setColor(Color.getViolet());
gr1.setLocation(4096);
gr1.setMedianPointLocation(75);
colorPoints.add(gr1);
colorPoints.get(1).setLocation(3000);
GradientTransparencyPoint gr2 = new GradientTransparencyPoint();
gr2.setOpacity(80.0);
gr2.setLocation(4096);
gr2.setMedianPointLocation(25);
transparencyPoints.add(gr2);
transparencyPoints.get(2).setLocation(3000);
settings.setColorPoints(colorPoints.toArray(new IGradientColorPoint[0]));
settings.setTransparencyPoints(transparencyPoints.toArray(new IGradientTransparencyPoint[0]));
fillLayer.update();
image.save(outputFile, new PsdOptions(image));
break;
}
}
}
String dataDir = Utils.getDataDir(GrayScaleSupportForAlpha.class) + "PSD/";
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "sample.psd")) {
// Create an instance of PngOptions class
PngOptions pngOptions = new PngOptions();
pngOptions.setColorType(PngColorType.TruecolorWithAlpha);
psdImage.save(dataDir + "GrayScaleSupportForAlpha_out.png", pngOptions);
}
String dataDir = Utils.getDataDir(ImportImageToPSDLayer.class) + "PSD/";
// Load a PSD file as an image and caste it into PsdImage
try (PsdImage image = (PsdImage) Image.load(dataDir + "sample.psd");
//Extract a layer from PSDImage
Layer layer = image.getLayers()[1];
// Create an image that is needed to be imported into the PSD file.
PsdImage drawImage = new PsdImage(200, 200)) {
// Fill image surface as needed.
Graphics g = new Graphics(drawImage);
g.clear(Color.getYellow());
// Call DrawImage method of the Layer class and pass the image instance.
layer.drawImage(new Point(10, 10), drawImage);
// Save the results to output path.
image.save(dataDir + "ImportImageToPSDLayer_out.psd");
}
String dataDir = Utils.getDataDir(LayerCreationDateTime.class) + "PSD/";
String sourceName = dataDir + "OneLayer.psd";
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage im = (PsdImage) Image.load(sourceName)) {
Layer layer = im.getLayers()[0];
Date creationDateTime = layer.getLayerCreationDateTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date expectedDateTime = new Date("2018/7/17 8:57:24");
Assert.areEqual(expectedDateTime, creationDateTime);
Date now = new Date();
Layer createdLayer = im.addLevelsAdjustmentLayer();
}
String dataDir = Utils.getDataDir(LayerEffectsForPSD.class) + "PSD/";
String sourceFileName = dataDir + "LayerWithText.psd";
String exportPath = dataDir + "LayerEffectsForPSD.png";
PsdLoadOptions loadOptions = new PsdLoadOptions();
loadOptions.setLoadEffectsResource(true);
loadOptions.setUseDiskForLoadEffectsResource(true);
try (PsdImage image = (PsdImage) Image.load(sourceFileName, loadOptions)) {
PngOptions options = new PngOptions();
options.setColorType(PngColorType.TruecolorWithAlpha);
image.save(exportPath, options);
}
String dataDir = Utils.getDataDir(LoadImageToPSD.class) + "PSD/";
String filePath = dataDir + "PsdExample.psd";
String outputFilePath = dataDir + "PsdResult.psd";
try (PsdImage image = new PsdImage(200, 200);
Image im = Image.load(filePath)) {
Layer layer = null;
try {
layer = new Layer((RasterImage) im, false);
image.addLayer(layer);
} catch (Exception e) {
if (layer != null) {
layer.dispose();
}
System.out.println(e);
}
}
String dataDir = Utils.getDataDir(ManageBrightnessContrastAdjustmentLayer.class) + "PSD/";
// Brightness/Contrast layer editing
String sourceFileName = dataDir + "BrightnessContrastModern.psd";
String psdPathAfterChange = dataDir + "BrightnessContrastModernChanged.psd";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < im.getLayers().length; i++) {
if (im.getLayers()[i] instanceof BrightnessContrastLayer) {
BrightnessContrastLayer brightnessContrastLayer = (BrightnessContrastLayer) im.getLayers()[i];
brightnessContrastLayer.setBrightness(50);
brightnessContrastLayer.setContrast(50);
}
}
// Save PSD
im.save(psdPathAfterChange);
}
String dataDir = Utils.getDataDir(ManageChannelMixerAdjusmentLayer.class) + "PSD/";
// Rgb Channel Mixer
String sourceFileName = dataDir + "ChannelMixerAdjustmentLayerRgb.psd";
String psdPathAfterChange = dataDir + "ChannelMixerAdjustmentLayerRgbChanged.psd";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < im.getLayers().length; i++) {
if (im.getLayers()[i] instanceof RgbChannelMixerLayer) {
RgbChannelMixerLayer rgbLayer = (RgbChannelMixerLayer) im.getLayers()[i];
rgbLayer.getRedChannel().setBlue((short) 100);
rgbLayer.getBlueChannel().setGreen((short) -100);
rgbLayer.getGreenChannel().setConstant((short) 50);
}
}
im.save(psdPathAfterChange);
}
// Adding the new layer(Cmyk for this example)
sourceFileName = dataDir + "CmykWithAlpha.psd";
psdPathAfterChange = dataDir + "ChannelMixerAdjustmentLayerCmykChanged.psd";
try (PsdImage img = (PsdImage) Image.load(sourceFileName)) {
ChannelMixerLayer newlayer = img.addChannelMixerAdjustmentLayer();
newlayer.getChannelByIndex(2).setConstant((short) 50);
newlayer.getChannelByIndex(0).setConstant((short) 50);
img.save(psdPathAfterChange);
}
String dataDir = Utils.getDataDir(ManageExposureAdjustmentLayer.class) + "PSD/";
// Exposure layer editing
String sourceFileName = dataDir + "ExposureAdjustmentLayer.psd";
String psdPathAfterChange = dataDir + "ExposureAdjustmentLayerChanged.psd";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < im.getLayers().length; i++) {
if (im.getLayers()[i] instanceof ExposureLayer) {
ExposureLayer expLayer = (ExposureLayer) im.getLayers()[i];
expLayer.setExposure(2);
expLayer.setOffset(-0.25f);
expLayer.setGammaCorrection(0.5f);
}
}
im.save(psdPathAfterChange);
}
// Exposure layer adding
sourceFileName = dataDir + "PhotoExample.psd";
psdPathAfterChange = dataDir + "PhotoExampleAddedExposure.psd";
try (PsdImage img = (PsdImage) Image.load(sourceFileName)) {
ExposureLayer newlayer = img.addExposureAdjustmentLayer(10, -0.25f, 2f);
img.save(psdPathAfterChange);
}
String dataDir = Utils.getDataDir(ManagePhotoFilterAdjustmentLayer.class) + "PSD/";
// Photo Filter layer editing
String sourceFileName = dataDir + "PhotoFilterAdjustmentLayer.psd";
String psdPathAfterChange = dataDir + "PhotoFilterAdjustmentLayerChanged.psd";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < im.getLayers().length; i++) {
if (im.getLayers()[i] instanceof PhotoFilterLayer) {
PhotoFilterLayer photoLayer = (PhotoFilterLayer) im.getLayers()[i];
photoLayer.setColor(Color.fromArgb(255, 60, 60));
photoLayer.setDensity(78);
photoLayer.setPreserveLuminosity(false);
}
}
im.save(psdPathAfterChange);
}
// Photo Filter layer adding
sourceFileName = dataDir + "PhotoExample.psd";
psdPathAfterChange = dataDir + "PhotoExampleAddedPhotoFilter.psd";
try (PsdImage img = (PsdImage) Image.load(sourceFileName)) {
PhotoFilterLayer layer = img.addPhotoFilterLayer(Color.fromArgb(25, 255, 35));
img.save(psdPathAfterChange);
}
String dataDir = Utils.getDataDir(MergeOnePSDlayerToOther.class) + "PSD/";
String sourceFile1 = dataDir + "FillOpacitySample.psd";
String sourceFile2 = dataDir + "ThreeRegularLayersSemiTransparent.psd";
String exportPath = dataDir + "MergedLayersFromTwoDifferentPsd.psd";
try (PsdImage im1 = (PsdImage) Image.load(sourceFile1);
PsdImage im2 = (PsdImage) Image.load(sourceFile2)) {
Layer layer1 = im1.getLayers()[1];
Layer layer2 = im2.getLayers()[0];
layer1.mergeLayerTo(layer2);
im2.save(exportPath);
}
String dataDir = Utils.getDataDir(MergePSDLayers.class) + "PSD/";
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "layers.psd")) {
// Create JPEG option class object, Set its properties and save image
JpegOptions jpgOptions = new JpegOptions();
psdImage.save(dataDir + "MergePSDlayers_output.jpg", jpgOptions);
}
String dataDir = Utils.getDataDir(PossibilityToFlattenLayers.class) + "PSD/";
// Flatten whole PSD
String sourceFileName = dataDir + "ThreeRegularLayersSemiTransparent.psd";
String exportPath = dataDir + "ThreeRegularLayersSemiTransparentFlattened.psd";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
im.flattenImage();
im.save(exportPath);
}
// Merge one layer in another
exportPath = dataDir + "ThreeRegularLayersSemiTransparentFlattenedLayerByLayer.psd";
try (PsdImage img = (PsdImage) Image.load(sourceFileName)) {
Layer bottomLayer = img.getLayers()[0];
Layer middleLayer = img.getLayers()[1];
Layer topLayer = img.getLayers()[2];
Layer layer1 = img.mergeLayers(bottomLayer, middleLayer);
Layer layer2 = img.mergeLayers(layer1, topLayer);
// Set up merged layers
img.setLayers(new Layer[]{layer2});
img.save(exportPath);
}
String dataDir = Utils.getDataDir(RenderingExportOfChannelMixerAdjusmentLyer.class) + "PSD/";
// Rgb Channel Mixer
String sourceFileName = dataDir + "ChannelMixerAdjustmentLayerRgb.psd";
String psdPathAfterChange = dataDir + "ChannelMixerAdjustmentLayerRgbChanged.psd";
String pngExportPath = dataDir + "ChannelMixerAdjustmentLayerRgbChanged.png";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < im.getLayers().length; i++) {
if (im.getLayers()[i] instanceof RgbChannelMixerLayer) {
RgbChannelMixerLayer rgbLayer = (RgbChannelMixerLayer) im.getLayers()[i];
rgbLayer.getRedChannel().setBlue((short) 100);
rgbLayer.getBlueChannel().setGreen((short) -100);
rgbLayer.getGreenChannel().setConstant((short) 50);
}
}
// Save PSD
im.save(psdPathAfterChange);
// Save PNG
PngOptions saveOptions = new PngOptions();
saveOptions.setColorType(PngColorType.TruecolorWithAlpha);
im.save(pngExportPath, saveOptions);
}
// Cmyk Channel Mixer
sourceFileName = dataDir + "ChannelMixerAdjustmentLayerCmyk.psd";
psdPathAfterChange = dataDir + "ChannelMixerAdjustmentLayerCmykChanged.psd";
pngExportPath = dataDir + "ChannelMixerAdjustmentLayerCmykChanged.png";
try (PsdImage img = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < img.getLayers().length; i++) {
if (img.getLayers()[i] instanceof CmykChannelMixerLayer) {
CmykChannelMixerLayer cmykLayer = (CmykChannelMixerLayer) img.getLayers()[i];
cmykLayer.getCyanChannel().setBlack((short) 20);
cmykLayer.getMagentaChannel().setYellow((short) 50);
cmykLayer.getYellowChannel().setCyan((short) -25);
cmykLayer.getBlackChannel().setYellow((short) 25);
}
}
// Save PSD
img.save(psdPathAfterChange);
// Save PNG
PngOptions options = new PngOptions();
options.setColorType(PngColorType.TruecolorWithAlpha);
img.save(pngExportPath, options);
}
String dataDir = Utils.getDataDir(RenderingExposureAdjustmentLayer.class) + "PSD/";
// Exposure layer editing
String sourceFileName = dataDir + "ExposureAdjustmentLayer.psd";
String psdPathAfterChange = dataDir + "ExposureAdjustmentLayerChanged.psd";
String pngExportPath = dataDir + "ExposureAdjustmentLayerChanged.png";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < im.getLayers().length; i++) {
if (im.getLayers()[i] instanceof ExposureLayer) {
ExposureLayer expLayer = (ExposureLayer) im.getLayers()[i];
expLayer.setExposure(2);
expLayer.setOffset(-0.25f);
expLayer.setGammaCorrection(0.5f);
}
}
// Save PSD
im.save(psdPathAfterChange);
// Save PNG
PngOptions saveOptions = new PngOptions();
saveOptions.setColorType(PngColorType.TruecolorWithAlpha);
im.save(pngExportPath, saveOptions);
// Exposure layer adding
sourceFileName = dataDir + "PhotoExample.psd";
psdPathAfterChange = dataDir + "PhotoExampleAddedExposure.psd";
pngExportPath = dataDir + "PhotoExampleAddedExposure.png";
PsdImage img = (PsdImage) Image.load(sourceFileName);
ExposureLayer newlayer = img.addExposureAdjustmentLayer(2, -0.25f, 2f);
// Save PSD
img.save(psdPathAfterChange);
// Save PNG
PngOptions options = new PngOptions();
options.setColorType(PngColorType.TruecolorWithAlpha);
img.save(pngExportPath, options);
}
String dataDir = Utils.getDataDir(RenderingOfCurvesAdjustmentLayer.class) + "PSD/";
// Curves layer editing
String sourceFileName = dataDir + "CurvesAdjustmentLayer";
String psdPathAfterChange = dataDir + "CurvesAdjustmentLayerChanged";
String pngExportPath = dataDir + "CurvesAdjustmentLayerChanged";
for (int j = 1; j < 2; j++) {
try (PsdImage im = (PsdImage) Image.load(sourceFileName + Integer.toString(j) + ".psd")) {
for (int i = 0; i < im.getLayers().length; i++) {
if (im.getLayers()[i] instanceof CurvesLayer) {
CurvesLayer curvesLayer = (CurvesLayer) im.getLayers()[i];
if (curvesLayer.isDiscreteManagerUsed()) {
CurvesDiscreteManager manager = (CurvesDiscreteManager) curvesLayer.getCurvesManager();
for (int k = 10; k < 50; k++) {
manager.setValueInPosition(0, (byte) k, (byte) (15 + (k * 2)));
}
} else {
CurvesContinuousManager manager = (CurvesContinuousManager) curvesLayer.getCurvesManager();
manager.addCurvePoint((byte) 0, (byte) 50, (byte) 100);
manager.addCurvePoint((byte) 0, (byte) 150, (byte) 130);
}
}
}
// Save PSD
im.save(psdPathAfterChange + Integer.toString(j) + ".psd");
// Save PNG
PngOptions saveOptions = new PngOptions();
saveOptions.setColorType(PngColorType.TruecolorWithAlpha);
im.save(pngExportPath + Integer.toString(j) + ".png", saveOptions);
}
}
String dataDir = Utils.getDataDir(RenderingOfLevelAdjustmentLayer.class) + "PSD/";
String sourceFileName = dataDir + "LevelsAdjustmentLayer.psd";
String psdPathAfterChange = dataDir + "LevelsAdjustmentLayerChanged.psd";
String pngExportPath = dataDir + "LevelsAdjustmentLayerChanged.png";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
for (int i = 0; i < im.getLayers().length; i++) {
if (im.getLayers()[i] instanceof LevelsLayer) {
LevelsLayer levelsLayer = (LevelsLayer) im.getLayers()[i];
LevelChannel channel = levelsLayer.getChannel(0);
channel.setInputMidtoneLevel(2.0f);
channel.setInputShadowLevel((short) 10);
channel.setInputHighlightLevel((short) 230);
channel.setOutputShadowLevel((short) 20);
channel.setOutputHighlightLevel((short) 200);
}
}
// Save PSD
im.save(psdPathAfterChange);
// Save PNG
PngOptions saveOptions = new PngOptions();
saveOptions.setColorType(PngColorType.TruecolorWithAlpha);
im.save(pngExportPath, saveOptions);
}
String dataDir = Utils.getDataDir(RenderingOfRotatedTextLayer.class) + "PSD/";
String sourceFileName = dataDir + "TransformedText.psd";
String exportPath = dataDir + "TransformedTextExport.psd";
String exportPathPng = dataDir + "TransformedTextExport.png";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
PngOptions opt = new PngOptions();
opt.setColorType(PngColorType.Grayscale);
im.save(exportPath);
im.save(exportPathPng, opt);
}
}
String dataDir = Utils.getDataDir(SheetColorHighlighting.class) + "PSD/";
String sourceFileName = dataDir + "SheetColorHighlightExample.psd";
String exportPath = dataDir + "SheetColorHighlightExampleChanged.psd";
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
Layer layer1 = im.getLayers()[0];
Assert.areEqual(SheetColorHighlightEnum.Violet, layer1.getSheetColorHighlight());
Layer layer2 = im.getLayers()[1];
Assert.areEqual(SheetColorHighlightEnum.Orange, layer2.getSheetColorHighlight());
layer1.setSheetColorHighlight(SheetColorHighlightEnum.Yellow);
im.save(exportPath);
}
String dataDir = Utils.getDataDir(StrokeEffectWithColorFill.class) + "PSD/";
// Implement rendering of Stroke effect with Color Fill for export
String sourceFileName = dataDir + "StrokeComplex.psd";
String exportPath = dataDir + "StrokeComplexRendering.psd";
String exportPathPng = dataDir + "StrokeComplexRendering.png";
PsdLoadOptions loadOptions = new PsdLoadOptions();
loadOptions.setLoadEffectsResource(true);
try (PsdImage im = (PsdImage) Image.load(sourceFileName, loadOptions)) {
for (int i = 0; i < im.getLayers().length; i++) {
StrokeEffect effect = (StrokeEffect) im.getLayers()[i].getBlendingOptions().getEffects()[0];
ColorFillSettings settings = (ColorFillSettings) effect.getFillSettings();
settings.setColor(Color.getDeepPink());
}
// Save psd
im.save(exportPath, new PsdOptions());
PngOptions option = new PngOptions();
option.setColorType(PngColorType.TruecolorWithAlpha);
// Save png
im.save(exportPathPng, option);
}
public static void main(String[] args) throws InterruptedException {
String dataDir = Utils.getDataDir(SupportForInterruptMonitor.class) + "PSD/";
ImageOptionsBase saveOptions = new PngOptions();
InterruptMonitor monitor = new InterruptMonitor();
SaveImageWorker worker = new SaveImageWorker(dataDir + "big.psb", dataDir + "big_out.png", saveOptions, monitor);
Thread thread = new Thread(worker);
try {
thread.start();
// The timeout should be less than the time required for full image conversion (without interruption).
Thread.sleep(3000);
// Interrupt the process
System.out.format("Interrupting the save thread #%d at %s\n", thread.getId(), new Date().toString());
monitor.interrupt();
// Wait for interruption...
thread.join();
} finally {
// If the file to be deleted does not exist, no exception is thrown.
File f = new File(dataDir + "big_out.png");
f.delete();
}
}
}
/**
* Initiates image conversion and waits for its interruption.
*/
class SaveImageWorker implements Runnable {
/**
* The path to the input image.
*/
private final String inputPath;
/**
* The path to the output image.
*/
private final String outputPath;
/**
* The interrupt monitor.
*/
private final InterruptMonitor monitor;
/**
* The save options.
*/
private final ImageOptionsBase saveOptions;
/**
* Initializes a new instance of the SaveImageWorker class.
*
* @param inputPath The path to the input image.
* @param outputPath The path to the output image.
* @param saveOptions The save options.
* @param monitor The interrupt monitor.
*/
public SaveImageWorker(String inputPath, String outputPath, ImageOptionsBase saveOptions, InterruptMonitor monitor) {
this.inputPath = inputPath;
this.outputPath = outputPath;
this.saveOptions = saveOptions;
this.monitor = monitor;
}
/**
* Tries to convert image from one format to another. Handles interruption.
*/
public void run() {
Image image = Image.load(this.inputPath);
try {
InterruptMonitor.setThreadLocalInstance(this.monitor);
try {
image.save(this.outputPath, this.saveOptions);
} catch (OperationInterruptedException e) {
System.out.format("The save thread #%d finishes at %s\n", Thread.currentThread().getId(), new Date().toString());
System.out.println(e);
} catch (Exception e) {
System.out.println(e);
} finally {
InterruptMonitor.setThreadLocalInstance(null);
}
} finally {
image.dispose();
}
}
}
String dataDir = Utils.getDataDir(SupportLayerForPSD.class) + "PSD/";
String sourceFileName = dataDir + "layers.psd";
String output = dataDir + "layers.png";
PsdLoadOptions imageLoadOptions = new PsdLoadOptions();
imageLoadOptions.setLoadEffectsResource(true);
imageLoadOptions.setUseDiskForLoadEffectsResource(true);
try (PsdImage image = (PsdImage) Image.load(sourceFileName, imageLoadOptions)) {
PngOptions saveOptions = new PngOptions();
saveOptions.setColorType(PngColorType.TruecolorWithAlpha);
image.save(output, saveOptions);
}
String dataDir = Utils.getDataDir(SupportOfAdjusmentLayers.class) + "PSD/";
// Channel Mixer Adjustment Layer
String sourceFileName1 = dataDir + "ChannelMixerAdjustmentLayer.psd";
String exportPath1 = dataDir + "ChannelMixerAdjustmentLayerChanged.psd";
try (PsdImage im = (PsdImage) Image.load(sourceFileName1)) {
for (int i = 0; i < im.getLayers().length; i++) {
if (im.getLayers()[i] instanceof AdjustmentLayer) {
AdjustmentLayer adjustmentLayer = (AdjustmentLayer) im.getLayers()[i];
if (adjustmentLayer != null) {
adjustmentLayer.mergeLayerTo(im.getLayers()[0]);
}
}
}
// Save PSD
im.save(exportPath1);
}
// Levels adjustment layer
String sourceFileName2 = dataDir + "LevelsAdjustmentLayerRgb.psd";
String exportPath2 = dataDir + "LevelsAdjustmentLayerRgbChanged.psd";
try (PsdImage img = (PsdImage) Image.load(sourceFileName2)) {
for (int i = 0; i < img.getLayers().length; i++) {
if (img.getLayers()[i] instanceof AdjustmentLayer) {
AdjustmentLayer adjustmentLayer = (AdjustmentLayer) img.getLayers()[i];
if (adjustmentLayer != null) {
adjustmentLayer.mergeLayerTo(img.getLayers()[0]);
}
}
}
// Save PSD
img.save(exportPath2);
}
String dataDir = Utils.getDataDir(SupportOfClippingMask.class) + "PSD/";
// Exposure layer editing
// Export of the psd with complex clipping mask
String sourceFileName = dataDir + "ClippingMaskComplex.psd";
String exportPath = dataDir + "ClippingMaskComplex.png";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
// Export to PNG
PngOptions saveOptions = new PngOptions();
saveOptions.setColorType(PngColorType.TruecolorWithAlpha);
im.save(exportPath, saveOptions);
}
String dataDir = Utils.getDataDir(SupportOfGdFlResource.class) + "PSD/";
String sourceFileName = dataDir + "ComplexGradientFillLayer.psd";
String exportPath = dataDir + "ComplexGradientFillLayer_after.psd";
PsdImage im = (PsdImage) Image.load(sourceFileName);
try {
for (Layer layer : im.getLayers()) {
if (layer instanceof FillLayer) {
FillLayer fillLayer = (FillLayer) layer;
for (LayerResource res : fillLayer.getResources()) {
if (res instanceof GdFlResource) {
// Reading
GdFlResource resource = (GdFlResource) res;
if (resource.getAlignWithLayer() != false ||
(Math.abs(resource.getAngle() - 45.0) > 0.001) ||
resource.getDither() != true ||
resource.getReverse() != false ||
!resource.getColor().equals(Color.getEmpty()) ||
Math.abs(resource.getHorizontalOffset() - (-39)) > 0.001 ||
Math.abs(resource.getVerticalOffset() - (-5)) > 0.001 ||
resource.getTransparencyPoints().length != 3 ||
resource.getColorPoints().length != 2) {
throw new RuntimeException("Resource Parameters were read wrong");
}
IGradientTransparencyPoint[] transparencyPoints = resource.getTransparencyPoints();
if (Math.abs(100.0 - transparencyPoints[0].getOpacity()) > 0.25 ||
transparencyPoints[0].getLocation() != 0 ||
transparencyPoints[0].getMedianPointLocation() != 50 ||
Math.abs(50.0 - transparencyPoints[1].getOpacity()) > 0.25 ||
transparencyPoints[1].getLocation() != 2048 ||
transparencyPoints[1].getMedianPointLocation() != 50 ||
Math.abs(100.0 - transparencyPoints[2].getOpacity()) > 0.25 ||
transparencyPoints[2].getLocation() != 4096 ||
transparencyPoints[2].getMedianPointLocation() != 50) {
throw new RuntimeException("Gradient Transparency Points were read Wrong");
}
IGradientColorPoint[] colorPoints = resource.getColorPoints();
if (!colorPoints[0].getColor().equals(Color.fromArgb(203, 64, 140)) ||
colorPoints[0].getLocation() != 0 ||
colorPoints[0].getMedianPointLocation() != 50 ||
!colorPoints[1].getColor().equals(Color.fromArgb(203, 0, 0)) ||
colorPoints[1].getLocation() != 4096 ||
colorPoints[1].getMedianPointLocation() != 50) {
throw new RuntimeException("Gradient Color Points were read Wrong");
}
// Editing
resource.setAngle(30.0);
resource.setDither(false);
resource.setAlignWithLayer(true);
resource.setReverse(true);
resource.setHorizontalOffset(25);
resource.setVerticalOffset(-15);
List<IGradientColorPoint> newColorPoints = new ArrayList<IGradientColorPoint>();
Collections.addAll(newColorPoints, resource.getColorPoints());
List<IGradientTransparencyPoint> newTransparencyPoints = new ArrayList<IGradientTransparencyPoint>();
Collections.addAll(newTransparencyPoints, resource.getTransparencyPoints());
GradientColorPoint gr = new GradientColorPoint();
gr.setMedianPointLocation(75);
gr.setLocation(4096);
gr.setColor(Color.getViolet());
newColorPoints.add(gr);
colorPoints[1].setLocation(3000);
GradientTransparencyPoint gr2 = new GradientTransparencyPoint();
gr2.setOpacity(80.0);
gr2.setLocation(4096);
gr2.setMedianPointLocation(25);
newTransparencyPoints.add(gr2);
transparencyPoints[2].setLocation(3000);
resource.setColorPoints(newColorPoints.toArray(new IGradientColorPoint[0]));
resource.setTransparencyPoints(newTransparencyPoints.toArray(new IGradientTransparencyPoint[0]));
im.save(exportPath);
}
break;
}
break;
}
}
} finally {
im.dispose();
}
String dataDir = Utils.getDataDir(SupportOfLayerMask.class) + "PSD/";
// Export of the psd with complex mask
String sourceFileName = dataDir + "MaskComplex.psd";
String exportPath = dataDir + "MaskComplex.png";
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
// Export to PNG
PngOptions saveOptions = new PngOptions();
saveOptions.setColorType(PngColorType.TruecolorWithAlpha);
im.save(exportPath, saveOptions);
}
String dataDir = Utils.getDataDir(SupportOfLinkedLayer.class) + "ModifyingAndConvertingImages/";
PsdImage psd = (PsdImage) Image.load(dataDir + "LinkedLayerexample.psd");
try {
Layer[] layers = psd.getLayers();
short layersLinkGroupId = psd.getLinkedLayersManager().linkLayers(layers);
short linkGroupId = psd.getLinkedLayersManager().getLinkGroupId(layers[0]);
if (layersLinkGroupId != linkGroupId) {
throw new Exception("layersLinkGroupId and linkGroupId are not equal.");
}
Layer[] linkedLayers = psd.getLinkedLayersManager().getLayersByLinkGroupId(linkGroupId);
for (Layer linkedLayer : linkedLayers) {
psd.getLinkedLayersManager().unlinkLayer(linkedLayer);
}
linkedLayers = psd.getLinkedLayersManager().getLayersByLinkGroupId(linkGroupId);
if (linkedLayers != null) {
throw new Exception("The linkedLayers field is not NULL.");
}
psd.save(dataDir + "LinkedLayerexample_output.psd");
} finally {
psd.dispose();
}
String dataDir = Utils.getDataDir(SupportOfRGBColor.class) + "PSD/";
// Support of RGB Color mode with 16bits/channel (64 bits per color)
String sourceFileName = dataDir + "inRgb16.psd";
String outputFilePathJpg = dataDir + "outRgb16.jpg";
String outputFilePathPsd = dataDir + "outRgb16.psd";
PsdLoadOptions options = new PsdLoadOptions();
try (PsdImage image = (PsdImage) Image.load(sourceFileName, options)) {
image.save(outputFilePathPsd, new PsdOptions(image));
JpegOptions saveOptions = new JpegOptions();
saveOptions.setQuality(100);
image.save(outputFilePathJpg, saveOptions);
}
String dataDir = Utils.getDataDir(SupportOfRotateLayer.class) + "PSD/";
String sourceFile = dataDir + "1.psd";
String pngPath = dataDir + "RotateFlipTest2617.png";
String psdPath = dataDir + "RotateFlipTest2617.psd";
int flipType = RotateFlipType.Rotate270FlipXY;
try (PsdImage im = (PsdImage) Image.load(sourceFile)) {
im.rotateFlip(flipType);
PngOptions options = new PngOptions();
options.setColorType(PngColorType.TruecolorWithAlpha);
im.save(pngPath, options);
im.save(psdPath);
}
String dataDir = Utils.getDataDir(SupportOfSoCoResource.class) + "ModifyingAndConvertingImages/";
String sourceFileName = dataDir + "ColorFillLayer.psd";
String exportPath = dataDir + "SoCoResource_Edited.psd";
PsdImage im = (PsdImage) Image.load(sourceFileName);
try {
for (Layer layer : im.getLayers()) {
if (layer instanceof FillLayer) {
FillLayer fillLayer = (FillLayer) layer;
for (LayerResource resource : fillLayer.getResources()) {
if (resource instanceof SoCoResource) {
SoCoResource socoResource = (SoCoResource) resource;
assert Color.fromArgb(63, 83, 141).equals(socoResource.getColor());
socoResource.setColor(Color.getRed());
break;
}
}
break;
}
im.save(exportPath);
}
} finally {
im.dispose();
}
String dataDir = Utils.getDataDir(SupportOfVmskResource.class) + "PSD/";
String sourceFileName = dataDir + "Rectangle.psd";
String exportPath = dataDir + "Rectangle_changed.psd";
PsdImage im = (PsdImage) Image.load(sourceFileName);
try {
VmskResource resource = getVmskResource(im);
// Reading
if (resource.isDisabled() != false ||
resource.isInverted() != false ||
resource.isNotLinked() != false ||
resource.getPaths().length != 7 ||
resource.getPaths()[0].getType() != VectorPathType.PathFillRuleRecord ||
resource.getPaths()[1].getType() != VectorPathType.InitialFillRuleRecord ||
resource.getPaths()[2].getType() != VectorPathType.ClosedSubpathLengthRecord ||
resource.getPaths()[3].getType() != VectorPathType.ClosedSubpathBezierKnotUnlinked ||
resource.getPaths()[4].getType() != VectorPathType.ClosedSubpathBezierKnotUnlinked ||
resource.getPaths()[5].getType() != VectorPathType.ClosedSubpathBezierKnotUnlinked ||
resource.getPaths()[6].getType() != VectorPathType.ClosedSubpathBezierKnotUnlinked) {
throw new RuntimeException("VmskResource was read wrong");
}
PathFillRuleRecord pathFillRule = (PathFillRuleRecord) resource.getPaths()[0];
InitialFillRuleRecord initialFillRule = (InitialFillRuleRecord) resource.getPaths()[1];
LengthRecord subpathLength = (LengthRecord) resource.getPaths()[2];
// Path fill rule doesn't contain any additional information
if (pathFillRule.getType() != VectorPathType.PathFillRuleRecord ||
initialFillRule.getType() != VectorPathType.InitialFillRuleRecord ||
initialFillRule.isFillStartsWithAllPixels() != false ||
subpathLength.getType() != VectorPathType.ClosedSubpathLengthRecord ||
subpathLength.isClosed() != true ||
subpathLength.isOpen() != false) {
throw new RuntimeException("VmskResource paths were read wrong");
}
// Editing
resource.setDisabled(true);
resource.setInverted(true);
resource.setNotLinked(true);
BezierKnotRecord bezierKnot = (BezierKnotRecord) resource.getPaths()[3];
bezierKnot.getPoints()[0] = new Point(0, 0);
bezierKnot = (BezierKnotRecord) resource.getPaths()[4];
bezierKnot.getPoints()[0] = new Point(8039797, 10905190);
initialFillRule.setFillStartsWithAllPixels(true);
subpathLength.setClosed(false);
im.save(exportPath);
} finally {
im.dispose();
}
static VmskResource getVmskResource(PsdImage image) {
Layer layer = image.getLayers()[1];
VmskResource resource = null;
LayerResource[] resources = layer.getResources();
for (int i = 0; i < resources.length; i++) {
if (resources[i] instanceof VmskResource) {
resource = (VmskResource) resources[i];
break;
}
}
if (resource == null) {
throw new RuntimeException("VmskResource not found");
}
return resource;
}
String dataDir = Utils.getDataDir(TextLayerBoundBox.class) + "PSD/";
String sourceFileName = dataDir + "LayerWithText.psd";
Size correctOpticalSize = new Size(127, 45);
Size correctBoundBox = new Size(172, 62);
try (PsdImage im = (PsdImage) Image.load(sourceFileName)) {
TextLayer textLayer = (TextLayer) im.getLayers()[1];
// Size of the layer is the size of the rendered area
Size opticalSize = textLayer.getSize();
Assert.areEqual(correctOpticalSize, opticalSize);
// TextBoundBox is the maximum layer size for Text Layer.
// In this area PS will try to fit your text
Size boundBox = textLayer.getTextBoundBox();
Assert.areEqual(correctBoundBox, boundBox);
}
String dataDir = Utils.getDataDir(UncompressedImageStreamObject.class) + "PSD/";
ByteArrayOutputStream ms = new ByteArrayOutputStream();
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "layers.psd")) {
PsdOptions saveOptions = new PsdOptions();
saveOptions.setCompressionMethod(CompressionMethod.Raw);
psdImage.save(ms, saveOptions);
// Now reopen the newly created image. But first seek to the beginning of stream since after saving seek is at the end now.
ms.reset();
PsdImage img = (PsdImage) Image.load(new ByteArrayInputStream(ms.toByteArray()));
Graphics graphics = new Graphics(psdImage);
// Perform graphics operations.
}
String dataDir = Utils.getDataDir(UncompressedImageUsingFile.class) + "PSD/";
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "layers.psd")) {
PsdOptions saveOptions = new PsdOptions();
saveOptions.setCompressionMethod(CompressionMethod.Raw);
psdImage.save(dataDir + "uncompressed_out.psd", saveOptions);
// Now reopen the newly created image.
PsdImage img = (PsdImage) Image.load(dataDir + "uncompressed_out.psd");
Graphics graphics = new Graphics(img);
// Perform graphics operations.
}
String dataDir = Utils.getDataDir(UpdateTextLayerInPSDFile.class) + "PSD/";
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "layers.psd")) {
for (int i = 0; i < psdImage.getLayers().length; i++) {
if (psdImage.getLayers()[i] instanceof TextLayer) {
TextLayer textLayer = (TextLayer) psdImage.getLayers()[i];
textLayer.updateText("test update", new Point(0, 0), 15.0f, Color.getPurple());
}
}
psdImage.save(dataDir + "UpdateTextLayerInPSDFile_out.psd");
}
String dataDir = Utils.getDataDir(CompressingTiff.class) + "ModifyingAndConvertingImages/";
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "layers.psd")) {
// Create an instance of TiffOptions for the resultant image
TiffOptions outputSettings = new TiffOptions(TiffExpectedFormat.Default);
// Set BitsPerSample, Compression, Photometric mode and graycale palette
int[] ushort = {4};
outputSettings.setBitsPerSample(ushort);
outputSettings.setCompression(TiffCompressions.Lzw);
outputSettings.setPhotometric(TiffPhotometrics.Palette);
outputSettings.setPalette(ColorPaletteHelper.create4BitGrayscale(true));
psdImage.save(dataDir + "SampleTiff_out.tiff", outputSettings);
}
String dataDir = Utils.getDataDir(ExportToMultiPageTiff.class) + "ModifyingAndConvertingImages/";
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "layers.psd")) {
// Initialize tiff frame list.
ArrayList<TiffFrame> frames = new ArrayList<TiffFrame>();
// Iterate over each layer of PsdImage and convert it to Tiff frame.
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffLzwCmyk);
for (int i = 0; i < psdImage.getLayers().length; i++) {
TiffFrame frame = new TiffFrame(psdImage.getLayers()[i], options);
frames.add(frame);
}
// Create a new TiffImage with frames created earlier and save to disk.
TiffFrame[] tiffFrames = frames.toArray(new TiffFrame[frames.size()]);
TiffImage tiffImage = new TiffImage(tiffFrames);
tiffImage.save(dataDir + "ExportToMultiPageTiff_output.tif");
}
String dataDir = Utils.getDataDir(TiffOptionsConfiguration.class) + "ModifyingAndConvertingImages/";
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "layers.psd")) {
// Create an instance of TiffOptions while specifying desired format Passsing TiffExpectedFormat.TiffJpegRGB will set the compression to Jpeg and BitsPerPixel according to the RGB color space.
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffJpegRgb);
psdImage.save(dataDir + "SampleTiff_out.tiff", options);
}
String dataDir = Utils.getDataDir(TIFFwithAdobeDeflateCompression.class) + "ModifyingAndConvertingImages/";
// Create an instance of TiffOptions and set its various properties
TiffOptions options = new TiffOptions(TiffExpectedFormat.Default);
int[] ushort = {8, 8, 8};
options.setBitsPerSample(ushort);
options.setPhotometric(TiffPhotometrics.Rgb);
options.setXresolution(new TiffRational(72));
options.setYresolution(new TiffRational(72));
options.setResolutionUnit(TiffResolutionUnits.Inch);
options.setPlanarConfiguration(TiffPlanarConfigs.Contiguous);
// Set the Compression to AdobeDeflate
options.setCompression(TiffCompressions.AdobeDeflate);
// Create a new TiffImage with specific size and TiffOptions settings
try (PsdImage tiffImage = new PsdImage(100, 100)) {
// Loop over the pixels to set the color to red
for (int j = 0; j < tiffImage.getHeight(); j++) {
for (int i = 0; i < tiffImage.getWidth(); i++) {
tiffImage.setPixel(i, j, Color.getRed());
}
}
// Save resultant image
tiffImage.save(dataDir + "TIFFwithAdobeDeflateCompression_output.tif");
}
String dataDir = Utils.getDataDir(TIFFWithDeflateCompression.class) + "ModifyingAndConvertingImages/";
// Load a PSD file as an image and cast it into PsdImage
try (PsdImage psdImage = (PsdImage) Image.load(dataDir + "layers.psd")) {
// Create an instance of TiffOptions while specifying desired format and compression
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffDeflateRgb);
options.setCompression(TiffCompressions.AdobeDeflate);
psdImage.save(dataDir + "TIFFwithDeflateCompression_out.tiff", options);
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-Java
PsdImage psdImage = null;
try {
psdImage = (PsdImage) Image.load(sourceDir + "ExportLayerGroupToImageSample.psd");
// folder with background
LayerGroup bgFolder = (LayerGroup) psdImage.getLayers()[0];
// folder with content
LayerGroup contentFolder = (LayerGroup) psdImage.getLayers()[4];
bgFolder.save(outputDir + "background.png", new PngOptions());
contentFolder.save(outputDir + "content.png", new PngOptions());
} finally {
if (psdImage != null) psdImage.dispose();
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-Java
private static final String actualPropertyValueIsWrongMessage = "Expected property value is not equal to actual value";
public static void main(String[] args) {
exampleSupportOfBlwhResource(
"BlackWhiteAdjustmentLayerStripesMask.psd",
0x28,
0x3c,
0x28,
0x3c,
0x14,
0x50,
false,
1,
"\0",
225.00045776367188,
211.00067138671875,
179.00115966796875,
-1977421,
-5925001);
exampleSupportOfBlwhResource(
"BlackWhiteAdjustmentLayerStripesMask2.psd",
0x80,
0x40,
0x20,
0x10,
0x08,
0x04,
true,
4,
"\0",
239.996337890625,
127.998046875,
63.9990234375,
-1015744,
-4963324);
System.out.println("BlwhResource updating works as expected. Press any key.");
}
private static void assertIsTrue(boolean condition, String message) {
if (!condition) {
throw new FormatException(message);
}
}
private static void exampleSupportOfBlwhResource(
String sourceFileName,
int reds,
int yellows,
int greens,
int cyans,
int blues,
int magentas,
boolean useTint,
int bwPresetKind,
String bwPresetFileName,
double tintColorRed,
double tintColorGreen,
double tintColorBlue,
int tintColor,
int newTintColor) {
String sourceDir = Utils.GetDataDir_PSD();
String outputDir = Utils.GetDataDir_Output();
String destinationFileName = outputDir + "Output" + sourceFileName;
boolean isRequiredResourceFound = false;
PsdImage im = null;
try {
im = (PsdImage) Image.load(sourceDir + sourceFileName);
for (Layer layer : im.getLayers()) {
for (LayerResource layerResource : layer.getResources()) {
if (layerResource instanceof BlwhResource) {
BlwhResource blwhResource = (BlwhResource) layerResource;
BlackWhiteAdjustmentLayer blwhLayer = (BlackWhiteAdjustmentLayer) layer;
isRequiredResourceFound = true;
assertIsTrue(blwhResource.getReds() == reds, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getYellows() == yellows, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getGreens() == greens, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getCyans() == cyans, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getBlues() == blues, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getMagentas() == magentas, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getUseTint() == useTint, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getTintColor() == tintColor, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getBwPresetKind() == bwPresetKind, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getBlackAndWhitePresetFileName().equals(bwPresetFileName), actualPropertyValueIsWrongMessage);
assertIsTrue(Math.abs(blwhLayer.getTintColorRed() - tintColorRed) < 1e-6, actualPropertyValueIsWrongMessage);
assertIsTrue(Math.abs(blwhLayer.getTintColorGreen() - tintColorGreen) < 1e-6, actualPropertyValueIsWrongMessage);
assertIsTrue(Math.abs(blwhLayer.getTintColorBlue() - tintColorBlue) < 1e-6, actualPropertyValueIsWrongMessage);
// Test editing and saving
blwhResource.setReds(reds - 15);
blwhResource.setYellows(yellows - 15);
blwhResource.setGreens(greens + 15);
blwhResource.setCyans(cyans + 15);
blwhResource.setBlues(blues - 15);
blwhResource.setMagentas(magentas - 15);
blwhResource.setUseTint(!useTint);
blwhResource.setBwPresetKind(4);
blwhResource.setBlackAndWhitePresetFileName("bwPresetFileName");
blwhLayer.setTintColorRed(tintColorRed - 60);
blwhLayer.setTintColorGreen(tintColorGreen - 60);
blwhLayer.setTintColorBlue(tintColorBlue - 60);
im.save(destinationFileName);
break;
}
}
}
} finally {
if (im != null) im.dispose();
}
assertIsTrue(isRequiredResourceFound, "The specified BlwhResource not found");
isRequiredResourceFound = false;
PsdImage im2 = null;
try {
im2 = (PsdImage) Image.load(destinationFileName);
for (Layer layer : im2.getLayers()) {
for (LayerResource layerResource : layer.getResources()) {
if (layerResource instanceof BlwhResource) {
BlwhResource blwhResource = (BlwhResource) layerResource;
BlackWhiteAdjustmentLayer blwhLayer = (BlackWhiteAdjustmentLayer) layer;
isRequiredResourceFound = true;
assertIsTrue(blwhResource.getReds() == reds - 15, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getYellows() == yellows - 15, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getGreens() == greens + 15, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getCyans() == cyans + 15, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getBlues() == blues - 15, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getMagentas() == magentas - 15, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getUseTint() == !useTint, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getTintColor() == newTintColor, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getBwPresetKind() == 4, actualPropertyValueIsWrongMessage);
assertIsTrue(blwhResource.getBlackAndWhitePresetFileName().equals("bwPresetFileName"), actualPropertyValueIsWrongMessage);
assertIsTrue(Math.abs(blwhLayer.getTintColorRed() - tintColorRed + 60) < 1e-6, actualPropertyValueIsWrongMessage);
assertIsTrue(Math.abs(blwhLayer.getTintColorGreen() - tintColorGreen + 60) < 1e-6, actualPropertyValueIsWrongMessage);
assertIsTrue(Math.abs(blwhLayer.getTintColorBlue() - tintColorBlue + 60) < 1e-6, actualPropertyValueIsWrongMessage);
break;
}
}
}
} finally {
if (im2 != null) im2.dispose();
}
assertIsTrue(isRequiredResourceFound, "The specified BlwhResource not found");
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-Java
public static void main(String[] args) {
String sourceDir = Utils.GetDataDir_PSD();
String outputDir = Utils.GetDataDir_Output();
String sourceFileName = sourceDir + "SampleForClblResource.psd";
String destinationFileName = outputDir + "SampleForClblResource_out.psd";
PsdImage im = null;
try {
im = (PsdImage) Image.load(sourceFileName);
ClblResource resource = getClblResource(im);
assertIsTrue(resource.getBlendClippedElements(), "The ClblResource.BlendClippedElements should be true");
// Test editing and saving
resource.setBlendClippedElements(false);
im.save(destinationFileName);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (im != null) im.dispose();
}
PsdImage im2 = null;
try {
im2 = (PsdImage) Image.load(destinationFileName);
ClblResource resource = getClblResource(im2);
assertIsTrue(!resource.getBlendClippedElements(), "The ClblResource.BlendClippedElements should change to false");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (im2 != null) im2.dispose();
}
System.out.println("SupportForClblResource executed successfully");
}
private static void assertIsTrue(boolean condition, String message) {
if (!condition) {
throw new FormatException(message);
}
}
private static ClblResource getClblResource(PsdImage im) throws Exception {
for (Layer layer : im.getLayers()) {
for (LayerResource layerResource : layer.getResources()) {
if (layerResource instanceof ClblResource) {
return (ClblResource) layerResource;
}
}
}
throw new Exception("The specified ClblResource not found");
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-Java
public static void main(String[] args) {
String sourceDir = Utils.GetDataDir_PSD();
String outputDir = Utils.GetDataDir_Output();
String sourceFileName = sourceDir + "SampleForInfxResource.psd";
String destinationFileName = outputDir + "SampleForInfxResource_out.psd";
boolean isRequiredResourceFound = false;
PsdImage im = null;
try {
im = (PsdImage) Image.load(sourceFileName);
for (Layer layer : im.getLayers()) {
for (LayerResource layerResource : layer.getResources()) {
if (layerResource instanceof InfxResource) {
InfxResource resource = (InfxResource) layerResource;
isRequiredResourceFound = true;
assertIsTrue(!resource.getBlendInteriorElements(), "The InfxResource.BlendInteriorElements should be false");
// Test editing and saving
resource.setBlendInteriorElements(true);
im.save(destinationFileName);
break;
}
}
}
} finally {
if (im != null) im.dispose();
}
assertIsTrue(isRequiredResourceFound, "The specified InfxResource not found");
isRequiredResourceFound = false;
PsdImage im2 = null;
try {
im2 = (PsdImage) Image.load(destinationFileName);
for (Layer layer : im2.getLayers()) {
for (LayerResource layerResource : layer.getResources()) {
if (layerResource instanceof InfxResource) {
InfxResource resource = (InfxResource) layerResource;
isRequiredResourceFound = true;
assertIsTrue(resource.getBlendInteriorElements(), "The InfxResource.BlendInteriorElements should change to true");
break;
}
}
}
} finally {
if (im2 != null) im2.dispose();
}
assertIsTrue(isRequiredResourceFound, "The specified InfxResource not found");
}
private static void assertIsTrue(boolean condition, String message) {
if (!condition) {
throw new FormatException(message);
}
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-Java
public static void main(String[] args) {
String sourceDir = Utils.GetDataDir_PSD();
String outputDir = Utils.GetDataDir_Output();
final String actualPropertyValueIsWrongMessage = "Expected property value is not equal to actual value";
String sourceFileName = sourceDir + "SampleForLspfResource.psd";
String destinationFileName = outputDir + "SampleForLspfResource_out.psd";
boolean isRequiredResourceFound = false;
PsdImage im = null;
try {
im = (PsdImage) Image.load(sourceFileName);
for (Layer layer : im.getLayers()) {
for (LayerResource layerResource : layer.getResources()) {
if (layerResource instanceof LspfResource) {
LspfResource resource = (LspfResource) layerResource;
isRequiredResourceFound = true;
assertIsTrue(!resource.isCompositeProtected(), actualPropertyValueIsWrongMessage);
assertIsTrue(!resource.isPositionProtected(), actualPropertyValueIsWrongMessage);
assertIsTrue(!resource.isTransparencyProtected(), actualPropertyValueIsWrongMessage);
// Test editing and saving
resource.setCompositeProtected(true);
assertIsTrue(resource.isCompositeProtected(), actualPropertyValueIsWrongMessage);
assertIsTrue(!resource.isPositionProtected(), actualPropertyValueIsWrongMessage);
assertIsTrue(!resource.isTransparencyProtected(), actualPropertyValueIsWrongMessage);
resource.setCompositeProtected(false);
resource.setPositionProtected(true);
assertIsTrue(!resource.isCompositeProtected(), actualPropertyValueIsWrongMessage);
assertIsTrue(resource.isPositionProtected(), actualPropertyValueIsWrongMessage);
assertIsTrue(!resource.isTransparencyProtected(), actualPropertyValueIsWrongMessage);
resource.setPositionProtected(false);
resource.setTransparencyProtected(true);
assertIsTrue(!resource.isCompositeProtected(), actualPropertyValueIsWrongMessage);
assertIsTrue(!resource.isPositionProtected(), actualPropertyValueIsWrongMessage);
assertIsTrue(resource.isTransparencyProtected(), actualPropertyValueIsWrongMessage);
resource.setCompositeProtected(true);
resource.setPositionProtected(true);
resource.setTransparencyProtected(true);
im.save(destinationFileName);
break;
}
}
}
} finally {
if (im != null) im.dispose();
}
assertIsTrue(isRequiredResourceFound, "The specified LspfResource not found");
isRequiredResourceFound = false;
PsdImage im2 = null;
try {
im2 = (PsdImage) Image.load(destinationFileName);
for (Layer layer : im2.getLayers()) {
for (LayerResource layerResource : layer.getResources()) {
if (layerResource instanceof LspfResource) {
LspfResource resource = (LspfResource) layerResource;
isRequiredResourceFound = true;
assertIsTrue(resource.isCompositeProtected(), actualPropertyValueIsWrongMessage);
assertIsTrue(resource.isPositionProtected(), actualPropertyValueIsWrongMessage);
assertIsTrue(resource.isTransparencyProtected(), actualPropertyValueIsWrongMessage);
break;
}
}
}
} finally {
if (im2 != null) im2.dispose();
}
assertIsTrue(isRequiredResourceFound, "The specified LspfResource not found");
System.out.println("LspfResource updating works as expected. Press any key.");
}
private static void assertIsTrue(boolean condition, String message) {
if (!condition) {
throw new FormatException(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment