目录

Image Processing

API Declaration

Add the following configuration to the features attribute in the manifest.json file:

{"name": "system.image"}

Module Import

Add the following configuration to the script element on the page where the API will be called:

import image from '@system.image'

Or

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

Application Scope

Item

Description

Applicable devices

Mobile phones, tablets, Vision products, and telematics devices

Applicable regions

Global

Definition

API

Description

image.compressImage(OBJECT)

Compresses an image in a specified path.

image.getImageInfo(OBJECT)

Obtains image information.

image.editImage(OBJECT)

Edits an image. The API provides a rectangle UI element for cropping an image and returns the path for storing the edited image.

image.getExifAttributes(OBJECT)

Obtains the Exif information about an image. Supported image formats: JPEG, PNG, WebP, HEIF, DNG, CR2, NEF, NRW, ARW, RW2, ORF, PEF, SRW, RAF, GIF

image.setExifAttributes(OBJECT)

Sets the Exif information about an image. This operation is performed on the original image, without creating new images. Supported image formats: JPEG, PNG

image.applyOperations(OBJECT)

Performs a series of edits on an image in sequence.

image.pickColor(OBJECT)

Obtains the code of the background or floating text color.

[h2]image.compressImage(OBJECT)

Description

Compresses an image in a specified path.

OBJECT parameters

Parameter

Type

Default Value

Mandatory

Description

uri

string

-

Yes

URI of the source file, which must be a local path. If an in-app resource path is used, it must be an absolute path.

quality

number

-

No

Image compression quality, ranging from 0 to 100.

ratio

number

-

No

Size compression multiple. The value is greater than 0. The greater the value is, the smaller the image size is. If both quality and ratio are set, compression based on ratio is performed first.

format

string

JPEG

No

Compression format. Supported formats: JPEG, PNG, WEBP

success

function

-

No

Callback upon success.

fail

function

-

No

Callback upon failure.

complete

function

-

No

Callback upon completion.

Parameters returned by success

Parameter

Type

Description

uri

string

URI of the successfully compressed image. The URI will be stored in the cache directory of the app.

Result codes returned by fail

Result Code

Description

202

Invalid parameter.

300

I/O error.

301

The file path does not exist.

Sample code

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);
    }
})

[h2]image.getImageInfo(OBJECT)

Description

Obtains image information.

OBJECT parameters

Parameter

Type

Mandatory

Description

uri

string

Yes

URI of the source file, which must be a local path. If an in-app resource path is used, it must be an absolute path.

success

function

No

Callback upon success.

fail

function

No

Callback upon failure.

complete

function

No

Callback upon completion.

Parameters returned by success

Parameter

Type

Description

uri

string

Image URI.

width

number

Image width, in pixels.

height

number

Image height, in pixels.

size

number

Image size, in bytes.

Result codes returned by fail

Result Code

Description

202

Invalid parameter.

300

I/O error.

301

The file path does not exist.

Sample code

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);
    }
})

[h2]image.editImage(OBJECT)

Description

Edits an image. The API provides a rectangle UI element for cropping an image and returns the path for storing the edited image.

This API also calls the image cropping capability. The image will be copied to the SD card during cropping, and then deleted from the SD card after the cropping is complete.

OBJECT parameters

Parameter

Type

Mandatory

Description

uri

string

Yes

URI of the source file, which must be a local path. If an in-app resource path is used, it must be an absolute path.

success

function

No

Callback upon success.

fail

function

No

Callback upon failure.

cancel

function

No

Callback upon cancellation triggered by a user.

complete

function

No

Callback upon completion.

Parameters returned by success

Parameter

Type

Description

uri

string

URI of the image file that has been edited.

Result codes returned by fail

Result Code

Description

202

Invalid parameter.

300

I/O error.

301

The file path does not exist.

Sample code

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

[h2]image.getExifAttributes(OBJECT) (1035+)

Description

Obtains the Exif information about an image. Supported image formats: JPEG, PNG, WebP, HEIF, DNG, CR2, NEF, NRW, ARW, RW2, ORF, PEF, SRW, RAF, GIF

OBJECT parameters

Parameter

Type

Mandatory

Description

uri

string

Yes

Image URI, which can be a data file path or an in-app resource path.

success

function

No

Callback upon success.

fail

function

No

Callback upon failure.

complete

function

No

Callback upon completion.

Parameters returned by success

Parameter

Type

Description

uri

string

Image path.

attributes

object

Exif information about an image.

Result codes returned by fail

Result Code

Description

202

Invalid parameter.

300

I/O error.

301

The file path does not exist.

Sample code

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

[h2]image.setExifAttributes(OBJECT) (1035+)

Description

Sets the Exif information about an image. This operation is performed on the original image, without creating new images. Supported image formats: JPEG, PNG

OBJECT parameters

Parameter

Type

Mandatory

Description

uri

string

Yes

Image URI, which can be a data file path or an in-app resource path.

attributes

object

Yes

List of Exif attributes to be configured. The following attributes are 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

success

function

No

Callback upon success.

fail

function

No

Callback upon failure.

complete

function

No

Callback upon completion.

Parameters returned by success

Parameter

Type

Description

uri

string

Image path.

attributes

object

Exif information about an image.

Result codes returned by fail

Result Code

Description

202

Invalid parameter.

300

I/O error.

301

The file path does not exist.

Sample code

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

[h2]image.applyOperations(OBJECT)

Description

Performs a series of edits on an image in sequence.

In this case, the result of the previous edit operation will serve as an input to the next edit operation. This is also true to the coordinate system, which takes the upper left corner of the image that is produced from the previous operation as the origin of coordinates for the next operation.

OBJECT parameters

Parameter

Type

Mandatory

Description

uri

string

Yes

URI of the source file, which must be a local path. If an in-app resource path is used, it must be an absolute path.

operations

objectarray

No

List of edit operations, which will be performed in the specified sequence. If this parameter is not set, images will not be edited but will still be saved as new images.

quality

integer

No

Image compression quality, ranging from 0 to 100. The default value is 75.

format

string

No

Format for saving an image. Supported formats: JPEG, PNG, WEBP The JPEG format is used by default.

success

function

No

Callback upon success.

fail

function

No

Callback upon failure.

complete

function

No

Callback upon completion.

Parameters returned by success

Parameter

Type

Description

uri

string

URI of the image file that has been edited, which is in the cache directory of the app.

Result codes returned by fail

Result Code

Description

202

Invalid parameter.

300

I/O error.

301

The file path does not exist.

The following edit operations are supported:

Sample code

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);
  }
})

[h2]image.pickColor(OBJECT) (1040+, Huawei Extended API, Not Formulated by the Vendor Alliance)

Description

Obtains the code of the background or floating text color. To call this API for a card, set the version number to 1045.

OBJECT parameters

Parameter

Type

Mandatory

Description

uri

string

Yes

URI of an image file, which can be an Internet or local image.

success

function

No

Callback upon success.

fail

function

No

Callback upon failure.

complete

function

No

Callback upon completion.

Parameters returned by success

Parameter

Type

Description

color

string

Code of the color that is obtained from the image, for example, #e5e5e5.

Result codes returned by fail

Result Code

Description

202

Invalid parameter.

300

I/O error.

301

The file path does not exist.

Sample code

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

Demo

<template>
  <!-- Only one root node is allowed in 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 that = 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
          });
          that.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 that = this;
      that.pickColorSrc = that.imagePath;
      image.pickColor({
        uri: that.pickColorSrc,
        success: function (data) {
          console.log(data.color);
          that.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 that = this;
      image.editImage({
        uri: "/Common/compress.jpg", //replace to your local image path
        success: function (data) {
          console.log(data.uri);
          that.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 that = 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);
          that.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>

Version Change History

Version

Date

Description

1040

2019-06-24

  • Added the getExifAttributes and setExifAttributes methods to set and obtain the Exif information of images respectively.
  • Added the image.pickColor method to obtain the code of the background or floating text color.