快速接入图片编辑器

为方便合作方开发者快速体验在web端打开图片编辑器,并进行图片编辑,完成下载。

最终效果图如下:

前期准备

AK、SK、appId(获取渠道:入驻指引

AK:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

SK:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

appId:xxxxxxxxxxxx

备注:合作方开发者自行替换成已申请的正式AK、SK、appId。

一、安装SDK并初始化

<code>npm i @gaoding/editor-sdk@next</code>

合作方开发者自己的前端:

<code>import { createImageEditor} from '@gaoding/editor-sdk';</code>
<code>const editor = createImageEditor({
  appId: 'xxxxxxxxxxxx',
  async authorize() {
     //在合作方开发者自己的后端发起POST请求获取稿定授权码并返回
       //'http://172.16.17.191:8098/demo/fetchAuthorizedCode'为合作方开发者自己后端接口
      const res = await axios.get('http://172.16.17.191:8098/demo/fetchAuthorizedCode');
      let data = JSON.parse(res.data);
      //data.code需确保为字符串,比如data.code的值为 "3efdc4e0a47c4fcca77d9d4befc68689"
      return data.code
  },
  
  //需开通权益
  //该方法返回权益,才能下载
  async getUseRightCert(info) {
			//在合作方开发者自己的后端发起POST请求获取权益码并返回
      //info参数作为请求参数需要传到后台
       //'http://172.16.17.191:8098/demo/fetchUseRightCert'为合作方开发者自己后端接口
      const res = await axios.get('http://172.16.17.191:8098/demo/fetchUseRightCert', {
    	params: {
      	info: info
        }
      });
      let data = JSON.parse(res.data);
      //data.use_cert需确保为字符串,比如data.use_cert的值为 "sadfsdfs"
      return data.use_cert
  }
});

</code>

合作方开发者自己的后端

TODO一、二、三需使用真实AK、SK、appId、uid

稿定授权码接口详情可移步 获取用户授权码

<code>private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

@ApiOperation(value = "获取开放平台授权码", httpMethod = "GET")
    @RequestMapping(value = "fetchAuthorizedCode", method = RequestMethod.GET)
    public String fetchAuthorizedCode() throws Exception {
        String code = "";

        // TODO 一、使用真实AK、SK
        String ak = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        String sk = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        String httpMethod = "GET";
        String uri = "/api/authorized/code/";
        // TODO 二、使用真实接口入参,包括app_id和uid
        String queryString = "app_id=xxxxxxxxxxxx&uid=xxxxxxx";
        long timestamp = System.currentTimeMillis() / 1000;
        String requestRaw = StringUtils.join(new String[]{httpMethod, "@", uri, "@", queryString, "@", Long.toString(timestamp)}, "");
        String signature = genHmac(requestRaw, sk);
        CloseableHttpClient client = HttpClientBuilder.create().build();
        // TODO 三、使用app_id和uid
        HttpGet HttpGet = new HttpGet("https://open-api.gaoding.com/api/authorized/code?app_id=xxxxxxxxxxxx&uid=xxxxxxx");
        CloseableHttpResponse response = null;
        try {
            HttpGet.addHeader("X-Timestamp", Long.toString(timestamp));
            HttpGet.addHeader("X-AccessKey", ak);
            HttpGet.addHeader("X-Signature", signature);
            response = client.execute(HttpGet);
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            code = EntityUtils.toString(responseEntity);
        } finally{
            try {
                // 释放资源
                if (client != null) {
                    client.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
        return code;
}

/**
     * 使用 HMAC-SHA1 签名方法对data进行签名
     * @param data 被签名的字符串
     * @param key  密钥
     * @return 加密后的字符串
 */
private String genHmac(String data, String key) {
    try {
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), HMAC_SHA1_ALGORITHM);
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        return new String(Base64.getEncoder().encode(mac.doFinal(data.getBytes(StandardCharsets.UTF_8))));
    } catch (Exception e) {
    }
    return null;
}
</code>
<code>{"code":"31b3b551-4d1f-425e-887e-f6ba588f14b5"}</code>

合作方开发者自己的后端

TODO一、二需使用真实AK、SK、appId、works_id(前端传入)、uid

稿定权益码接口详情可移步 获取权益码

<code>private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

@RequestMapping(value = "fetchUseRightCert", method = RequestMethod.GET)
public String fetchUseRightCert(MediaTabReq request) throws Exception {
    // TODO 一、使用真实AK、SK
    String ak = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    String sk = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    String httpMethod = "POST";
    String uri = "/api/use-cert/";
    String queryString = "";
    String userCert = "";
    JSONObject jsonBody = new JSONObject();
    // TODO 二、使用真实接口入参,可从前端传过来的info中取
    jsonBody.put("ability_code", "IE002"); //IE002表示图片编辑器权益
    jsonBody.put("app_id", "xxxxxxxxxxxx");
    jsonBody.put("works_id", "xxxxxxxxxxxxxxxxxxx");//作品ID,使用回调方法asyn getUseRightCert(info)中的info.workId
    jsonBody.put("uid", "xxxxxxx");
    long timestamp = System.currentTimeMillis() / 1000;

    String requestRaw = StringUtils.join(new String[]{httpMethod, "@", uri, "@", queryString, "@", Long.toString(timestamp), "@", jsonBody.toJSONString()}, "");
    String signature = genHmac(requestRaw, sk);
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost("https://open-api.gaoding.com/api/use-cert");
    CloseableHttpResponse response = null;
    try {
        //body有值,需要额外增加这行
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("X-Timestamp", Long.toString(timestamp));
        httpPost.addHeader("X-AccessKey", ak);
        httpPost.addHeader("X-Signature", signature);
        httpPost.setEntity(new StringEntity(jsonBody.toString()));
        response = client.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        System.out.println("响应状态为:" + response.getStatusLine());
        if (responseEntity != null) {
            userCert = EntityUtils.toString(responseEntity,"UTF-8");
        }

    } finally {
        try {
            // 释放资源
            if (client != null) {
                client.close();
            }
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return userCert;
}

/**
     * 使用 HMAC-SHA1 签名方法对data进行签名
     * @param data 被签名的字符串
     * @param key  密钥
     * @return 加密后的字符串
 */
private String genHmac(String data, String key) {
    try {
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), HMAC_SHA1_ALGORITHM);
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        return new String(Base64.getEncoder().encode(mac.doFinal(data.getBytes(StandardCharsets.UTF_8))));
    } catch (Exception e) {
    }
    return null;
}
</code>
<code>{"use_cert":"5f781baf-660e-490e-b2cf-fb842545f0ec"}</code>

二、调用图片编辑器方法

调用图片编辑器importImage方法,可打开图片编辑器,进行图片编辑并下载。

(如出现跨域,需在合作方服务器白名单加上稿定域名:https://open.gaoding.com

合作方开发者自己的前端

<code>let pic = [];
pic.push('https://cdn.dancf.com/fe-assets/20220630/0286976e0887613ad9889ec4b50da5a1.jpg?x-oss-process=image/resize,w_1848/interlace,1,image/format,webp')

editor.importImage(pic,{disableModules: ['panel.ajustment']}).then(res => {
  console.log("初始化:"+res)
  if (res) {

  }
})

//点击下载时,除了保存到个人库,直接浏览器下载
editor.onSave(({ files, workId, type, title }) => {
  let file = files[0];
  let url = URL.createObjectURL(file);
  let  a = document.createElement('a');
  a.href = url;
  a.download = title+'.'+type;
  a.click();
  editor.close();
})</code>

至此,合作方开发者已经完成web端图片编辑器的接入和使用啦~

想要了解图片编辑器更多细节,可移步到 图片编辑器