# Image Processing

Image compression and manipulation.

# Manifest Declaration

You need to declare the use of this API in the manifest's features member:

{"name": "system.image"}

# Module Import

Before using this service in a component, you need to import the module in the script section of the UX document.

import image from '@system.image' 

Or

let image = require("@system.image")

# Methods

This service defines the following methods:

# compressImage({uri,quality,ratio,format,success,fail,complete})

Method to compress an image.

# Arguments

This method requires an object with the following attributes:

  • uri (string). Mandatory attribute with the URI of the source file. If the resource is local, you need to use an absolute path.
  • quality (number). Optional attribute with the image compression quality (values between 0 and 100).
  • ratio (number). Optional attribute with the non-negative integer indicating the ratio of compression of the image. If both quality and ratio are specified, the system will perform the compression based on ratio first.
  • format (string). Optional attribute with bit rate of the compressed video, in bit/s. The default value is half of the original video bit rate. Restricted by the hardware platform, the actual bit rate after compression may not be the same as the configured bit rate.
  • success (function(res)). Optional callback function corresponding to the successful execution. The argument of the callback function is an object with the following member:
    • uri (string). URI of the compressed image. The file is stored in the cache directory of the app.
  • fail (function(mes, code)). Optional callback function corresponding to the failed execution. The possible codes are:
    • 202. Invalid parameter.
    • 300. I/O error.
    • 301. The file path does not exist.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

image.compressImage({ 
    uri: "tmp://abc.jpg", 
        quality:80, 
        ratio: 2, 
        format: "JPEG", 
    success: function(data) { 
        console.log(data.uri) 
    }, 
    fail: function(data, code) { 
        console.log("handling fail, code=" + code)
    } 
})

# getImageInfo({uri,success,fail,complete})

Method to get information about an image.

# Arguments

This method requires an object with the following attributes:

  • uri (string). Mandatory attribute with the URI of the source file. If the resource is local, you need to use an absolute path.
  • success (function(res)). Optional callback function corresponding to the successful execution. The argument of the callback function is an object with the following members:
    • uri (string). URI of the image. The file is stored in the cache directory of the app.
    • size (number) with the image file size, in bytes.
    • height (number) with the image height, in pixels.
    • width (number) with the image width, in pixels.
  • fail (function(mes, code)). Optional callback function corresponding to the failed execution. The possible codes are:
    • 202. Invalid parameter.
    • 300. I/O error.
    • 301. The file path does not exist.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

image.getImageInfo({ 
    uri: "tmp://abc.jpg", 
    success: function(data) { 
        console.log(data.uri + data.width + data.height + data.size) 
    }, 
    fail: function(data, code) { 
        console.log("handling fail, code=" + code); 
    } 
})

# editImage({uri,success,fail,cancel,complete})

Method to crop an image.

The method provides a UI element for cropping an image and returns the path of the edited image.

# Arguments

This method requires an object with the following attributes:

  • uri (string). Mandatory attribute with the URI of the source file, that must be locally stored. You need to use an absolute path.
  • success (function(res)). Optional callback function corresponding to the successful execution. The argument of the callback function is an object with the following member:
    • uri (string). URI of the image that was edited.
  • fail (function(mes, code)). Optional callback function corresponding to the failed execution. The possible codes are:
    • 202. Invalid parameter.
    • 300. I/O error.
    • 301. The file path does not exist.
  • cancel (function). Optional callback function to be executed when the process is cancelled.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

image.editImage({ 
    uri: "tmp://abc.jpg", 
    success: function(data.uri) { 
        console.log(data.uri) 
    }, 
    fail: function(data, code) { 
        console.log("handling fail, code=" + code); 
    } 
})

# getExifAttributes({uri,success,fail,complete})

Method to get the EXIF information about an image.

This method supports the following image formats: JPEG, PNG, WebP, HEIF, DNG, CR2, NEF, NRW, ARW, RW2, ORF, PEF, SRW, RAF, and GIF.

# Arguments

This method requires an object with the following attributes:

  • uri (string). Mandatory attribute with the URI of the source file.
  • success (function(res)). Optional callback function corresponding to the successful execution. The argument of the callback function is an object with the following members:
    • uri (string). URI of the image.
    • attributes (object). EXIF information about the image.
  • fail (function(mes, code)). Optional callback function corresponding to the failed execution. The possible codes are:
    • 202. Invalid parameter.
    • 300. I/O error.
    • 301. The file path does not exist.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

image.getExifAttributes ({ 
    uri: "tmp://abc.jpg", 
    success: function(data) { 
        console.log(JSON.stringify(data)); 
    }, 
    fail: function(data, code) { 
        console.log("handling fail, code=" + code); 
    } 
})

# setExifAttributes({uri,attributes,success,fail,complete})

Method to set the EXIF metadata in an image.

This method supports the JPEG, and PNG formats.

# Arguments

This method requires an object with the following attributes:

  • uri (string). Mandatory attribute with the URI of the image.
  • attributes (object). Mandatory attribute with the EXIF metadata to be included into the image.
  • success (function(res)). Optional callback function corresponding to the successful execution. The argument of the callback function is an object with the following members:
    • uri (string). URI of the image.
    • attributes (object). Exit information about the image.
  • fail (function(mes, code)). Optional callback function corresponding to the failed execution. The possible codes are:
    • 202. Invalid parameter.
    • 300. I/O error.
    • 301. The file path does not exist.
  • complete (function). Optional callback function corresponding to the end of the execution.

EXIF metadata supported

Artist, BitsPerSample, Compression, Copyright, DateTime, ImageDescription, ImageLength, ImageWidth, JPEGInterchangeFormat, JPEGInterchangeFormatLength, Make, Model, Orientation, PhotometricInterpretation, PlanarConfiguration, PrimaryChromaticities, ReferenceBlackWhite, ResolutionUnit, RowsPerStrip, SamplesPerPixel, Software, StripByteCounts, StripOffsets, TransferFunction, WhitePoint, XResolution, YCbCrCoefficients, YCbCrPositioning, YCbCrSubSampling, YResolution, ApertureValue, BrightnessValue, CFAPattern, ColorSpace, ComponentsConfiguration, CompressedBitsPerPixel, Contrast, CustomRendered, DateTimeDigitized, DateTimeOriginal, DeviceSettingDescription, DigitalZoomRatio, ExifVersion, ExposureBiasValue, ExposureIndex, ExposureMode, ExposureProgram, ExposureTime, FNumber, FileSource, Flash, FlashEnergy, FlashpixVersion, FocalLength, FocalLengthIn35mmFilm, FocalPlaneResolutionUnit, FocalPlaneXResolution, FocalPlaneYResolution, GainControl, ISOSpeedRatings, ImageUniqueID, LightSource, MakerNote, MaxApertureValue, MeteringMode, NewSubfileType, OECF, PixelXDimension, PixelYDimension, RelatedSoundFile, Saturation, SceneCaptureType, SceneType, SensingMethod, Sharpness, ShutterSpeedValue, SpatialFrequencyResponse, SpectralSensitivity, SubfileType, SubSecTime, SubSecTimeDigitized, SubSecTimeOriginal, SubjectArea, SubjectDistance, SubjectDistanceRange, SubjectLocation, UserComment, WhiteBalance, GPSAltitude, GPSAltitudeRef, GPSAreaInformation, GPSDOP, GPSDateStamp, GPSDestBearing, GPSDestBearingRef, GPSDestDistance, GPSDestDistanceRef, GPSDestLatitude, GPSDestLatitudeRef, GPSDestLongitude, GPSDestLongitudeRef, GPSDifferential, GPSImgDirection, GPSImgDirectionRef, GPSLatitude, GPSLatitudeRef, GPSLongitude, GPSLongitudeRef, GPSMapDatum, GPSMeasureMode, GPSProcessingMethod, GPSSatellites, GPSSpeed, GPSSpeedRef, GPSStatus, GPSTimeStamp, GPSTrack, GPSTrackRef, GPSVersionID, InteroperabilityIndex, ThumbnailImageLength, ThumbnailImageWidth, DNGVersion, DefaultCropSize, ThumbnailImage, PreviewImageStart, PreviewImageLength, AspectFrame, SensorBottomBorder, SensorLeftBorder, SensorRightBorder, SensorTopBorder, ISO, JpgFromRaw

Example:

image.setExifAttributes({ 
    uri:"/common/img/xmad.jpg", 
    attributes:{ 
        Model:"iPhone X" 
    }, 
    success: function (data) { 
        console.log("success"); 
    }, 
    fail: function (data, code) { 
        console.log("applyOperation fail, code=" + code); 
    } 
})

# applyOperations({uri,operations,quality,format,success,fail,complete})

Method to apply edits on an image.

You can use the result of this method as an input to the next edit operation.

# Arguments

This method requires an object with the following attributes:

  • uri (string). Mandatory attribute with the URI of the image, that must be local. You need to represent it as an absolute path.
  • operations (array). Optional attribute with a list of objects with the edit operation, which will be performed in the specified sequence. If this parameter is not specified, the image will be saved as a new image but without any edit (see all the edit operations).
  • quality (number). Optional attribute with the image compression quality, with a value between 0 and 100. The default value is 75.
  • format (string). Optional attribute with the format of the resulting image. Supported formats: JPEG (by default), PNG, and WEBP.
  • success (function(res)). Optional callback function corresponding to the successful execution. The argument of the callback function is an object with the following member:
    • uri (string). URI of the resulting image, stored in the cache directory of the app.
  • fail (function(mes, code)). Optional callback function corresponding to the failed execution. The possible codes are:
    • 202. Invalid parameter.
    • 300. I/O error.
    • 301. The file path does not exist.
  • complete (function). Optional callback function corresponding to the end of the execution.
# Edit Operations

Every edit operation is specified through an object whose format varies depending on the edit type.

Image cropping object attributes:

  • action (string) Fixed to crop.
  • width (string). Mandatory attribute with the width of the cropped image.
  • height (string). Mandatory attribute with the height of the cropped image.
  • x (number). Optional attribute with the horizontal coordinate of the cropping start point (0 by default).
  • y (number). Optional attribute with the vertical coordinate of the cropping start point (0 by default).

The operation fails if the cropped area is outside the image range.

Image scale object attributes:

  • action (string) Fixed to scale.
  • scaleX (number). Optional attribute with the horizontal scaling ratio (1 by default, the same ratio).
  • scaleY (number). Optional attribute with the vertical scaling ration (1 by default, the same ratio).

Image rotation object attributes:

  • action (string) Fixed to rotate.
  • degree (number). Mandatory attribute with the rotation angle (in degrees).

Example:

image.applyOperations({ 
    uri: 'internal://cache/123.png', 
    operations: [ 
    { 
        action: 'scale', 
        scaleX: 0.5, 
        scaleY: 0.5 
    }, 
    { 
        action: 'crop', 
        width: 200, 
        height: 200 
    }, 
    { 
        action: 'rotate', 
        degree: 90, 
    } 
  ], 
  quality: 90, 
  format: 'webp', 
  success: function(data) { 
      console.log("handling success: " + data.uri); 
  }, 
  fail: function(data, code) { 
      console.log("handling fail, code=" + code); 
  } 
})

# pickColor({uri,success,fail,complete})

Method to get the background or the text color of an image.

# Arguments

This method requires an object with the following attributes:

  • uri (string). Mandatory attribute with the URI of the image (local or external).
  • success (function(res)). Optional callback function corresponding to the successful execution. The argument of the callback function is an object with the following member:
    • color (string). URI of the image.
  • fail (function(mes, code)). Optional callback function corresponding to the failed execution. The possible codes are:
    • 202. Invalid parameter.
    • 300. I/O error.
    • 301. The file path does not exist.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

image.pickColor({ 
    uri: "tmp://abc.jpg", 
    success: function(data) { 
        console.log(data.color) 
    }, 
    fail: function(data, code) { 
        console.log("handling fail, code=" + code); 
    } 
})

# Example

<template> 
  <div class="container"> 
    <input class="btn" type="button" value="compressImage" onclick="compressImage" /> 
    <input class="btn" type="button" value="getImageInfo" onclick="getImageInfo" /> 
    <input class="btn" type="button" value="editImage" onclick="editImage" /> 
    <input class="btn" type="button" value="applyOperations" onclick="applyOperations" /> 
    <input class="btn" type="button" value="pickColor" onclick="pickColor" /> 
    <input class="btn" type="button" value="Obtain Exif information" onclick="getExifAttributes" /> 
    <input class="btn" type="button" value="Set Exif information" onclick="setExifAttributes" /> 
    <text class="pickColor" style="background-color: {{pickedColor}}">pickedColor</text> 
    <image class="img" src="{{compressImageUri}}"></image> 
    <image class="img" src="{{editImageUri}}"></image> 
    <image class="img" src="{{applyOperationsImageUri}}"></image> 
  </div> 
</template> 
<style> 
  .container { 
    flex-direction: column; 
    align-content: center; 
    align-items: center; 
    padding: 20px; 
  } 
  .img { 
    margin-bottom: 50px; 
    margin-top: 50px; 
  } 
  .btn { 
    width: 300px; 
    height: 80px; 
    text-align: center; 
    margin-bottom: 50px; 
    color: #ffffff; 
    font-size: 30px; 
    background-color: #0faeff; 
  } 
  .pickColor { 
    width: 300px; 
    height: 80px; 
    text-align: center; 
    color: #000000; 
    font-size: 30px; 
    background-color: #0faeff;     
  } 
</style> 
<script> 
  import image from '@system.image' 
  import prompt from '@system.prompt' 
  module.exports = { 
    data: { 
      imagePath: "/Common/compress.jpg", //replace to your local image path 
      pickColorSrc: "", 
      pickedColor: "#0faeff", 
      compressImageUri: "", 
      editImageUri: "", 
      applyOperationsImageUri: "" 
    }, 
    compressImage: function () { 
      var self = this; 
      image.compressImage({ 
        uri: "/Common/compress.jpg",  //replace to your local image path 
        ratio: 2, 
        format: "JPEG", 
        success: function (data) { 
          console.log(data.uri); 
          prompt.showToast({ 
            message: "success:" + data.uri 
          }); 
          self.compressImageUri = data.uri 
        }, 
        fail: function (data, code) { 
          console.log("handling fail, code=" + code); 
          prompt.showToast({ 
            message: "handling fail, code=" + code + "----data" + data 
          }) 
        } 
      }) 
    }, 
    pickColor: function () { 
      var self = this; 
      self.pickColorSrc = self.imagePath; 
      image.pickColor({ 
        uri: self.pickColorSrc, 
        success: function (data) { 
          console.log(data.color); 
          self.pickedColor = data.color; 
        }, 
        fail: function (data, code) { 
          console.log("handling fail, code=" + code); 
        } 
      }); 
    }, 
    getImageInfo: function () { 
      image.getImageInfo({  
        uri: "/Common/compress.jpg", //replace to your local image path 
        success: function (data) { 
          console.log("uri:" + data.uri + "\n" + "width:" + data.width + "\n" + "height:" + data.height + "\n" + "size:" + data.size) 
          prompt.showToast({ 
            message: "uri:" + data.uri + "\n" + "width:" + data.width + "\n" + "height:" + data.height + "\n" + "size:" + data.size 
          }) 
        }, 
        fail: function (data, code) { 
          console.log("handling fail, code=" + code); 
          prompt.showToast({ 
            message: "code=" + code 
          }) 
        } 
      }) 
    }, 
    editImage: function () { 
      var self = this; 
      image.editImage({ 
        uri: "/Common/compress.jpg", //replace to your local image path 
        success: function (data) { 
          console.log(data.uri); 
          self.editImageUri = data.uri; 
        }, 
        cancel: function () { 
          console.log("edit cancel"); 
          prompt.showToast({ 
            message: "edit cancel" 
          }) 
        }, 
        fail: function (data, code) { 
          console.log("edit fail, code=" + code); 
          prompt.showToast({ 
            message: "edit fail, code=" + code 
          }) 
        } 
      }) 
    }, 
    applyOperations() { 
      var self = this; 
      image.applyOperations({ 
        uri: "/Common/compress.jpg", //replace to your local image path 
        operations: [ 
          { 
            action: 'scale', 
            scaleX: 0.5, 
            scaleY: 0.5 
          }, 
          { 
            action: 'crop', 
            width: 200, 
            height: 200 
          }, 
          { 
            action: 'rotate', 
            degree: 90, 
          } 
        ], 
        quality: 90, 
        format: 'webp', 
        success: function (data) { 
          console.log(data.uri); 
          self.applyOperationsImageUri = data.uri; 
        }, 
        fail: function (data, code) { 
          console.log("applyOperation fail, code=" + code); 
          prompt.showToast({ 
            message: "applyOperation fail, code=" + code 
          }) 
        } 
      }) 
    }, 
    getExifAttributes() { 
      image.getExifAttributes({ 
        uri: "/Common/compress.jpg", //replace to your local image path 
        success: function (data) { 
          console.log(JSON.stringify(data)); 
          prompt.showToast({ 
            message: JSON.stringify(data) 
          }) 
        }, 
        fail: function (data, code) { 
          console.log("applyOperation fail, code=" + code); 
          prompt.showToast({ 
            message: "applyOperation fail, code=" + code 
          }) 
        } 
      }); 
    }, 
    setExifAttributes() { 
      image.setExifAttributes({ 
        uri: "/Common/compress.jpg", //replace to your local image path 
        attributes: { 
          Model: "iphone" 
        }, 
        success: function (data) { 
          console.log("success"); 
          prompt.showToast({ 
            message: "Setting successful" 
          }) 
        }, 
        fail: function (data, code) { 
          console.log("applyOperation fail, code=" + code); 
          prompt.showToast({ 
            message: "applyOperation fail, code=" + code 
          }) 
        } 
      }); 
    } 
  } 
</script>