Aplique desfoque em uma imagem inteira ou em parte de uma imagem no Object Storage Service (OSS) para proteger informações sensíveis ou aprimorar o efeito visual.
Cenários
Proteja informações sensíveis: antes de publicar uma imagem que contenha dados sensíveis, como a placa de um veículo ou o rosto de uma pessoa, aplique um desfoque parcial para ocultar esses detalhes.
Composição de imagens: ao combinar várias camadas de imagem, aplique um efeito de desfoque para suavizar as bordas entre as camadas. Isso cria um efeito visual mais contínuo.
Oculte a baixa resolução: se uma imagem tiver baixa resolução e não for adequada para exibição em alta definição, aplique um desfoque moderado para reduzir o aspecto pixelizado.
Métodos
Defina os parâmetros de processamento de imagem usando a URL do arquivo, um kit de desenvolvimento de software (SDK) ou uma API. O método de URL do arquivo aplica-se apenas a imagens com acesso público. Para imagens privadas, use um SDK ou uma API. Para obter mais informações, consulte Métodos de processamento de imagem.
Imagens com acesso público
Para imagens com permissões de leitura pública ou de leitura e gravação pública, adicione parâmetros de processamento diretamente à URL da imagem. Dessa forma, qualquer pessoa poderá acessar a imagem processada de forma permanente e anônima.
O exemplo a seguir mostra como adicionar o parâmetro ?x-oss-process=image/blur,parameter_value à URL de uma imagem. Substitua parameter_value pelos parâmetros e valores específicos descritos na seção Parâmetros. Também é possível combinar vários parâmetros.
|
URL da imagem de origem |
URL da imagem com parâmetros de processamento |
|
https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg |
Imagens privadas
Usar um SDK do Alibaba Cloud
Os exemplos de código a seguir mostram como adicionar um efeito de desfoque a imagens privadas com SDKs comuns. Para exemplos com outros SDKs, consulte Visão geral do SDK.
Java
É necessário usar o Java SDK 3.17.4 ou posterior.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;
public class Demo {
public static void main(String[] args) throws Throwable {
// In this example, the endpoint of the China (Hangzhou) region is used. Replace it with the actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region that corresponds to the endpoint. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name.
String objectName = "src.jpg";
// Specify the full path of the local file. Example: D:\\localpath\\example-new.jpg. If the specified local file exists, it is overwritten. Otherwise, a new file is created.
String pathName = "D:\\dest.jpg";
// Create an OSSClient instance.
// When the OSSClient instance is no longer used, call the shutdown method to release the resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Apply a blur to the image with a radius of 10 and a standard deviation of 10.
String image = "image/blur,r_10,s_10";
GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
request.setProcess(image);
// Name the processed image dest.jpg and save it to your local machine.
// If you specify only the file name (for example, dest.jpg) without a local path, the file is saved to the local path of the project by default.
ossClient.getObject(request, new File("D:\\dest.jpg"));
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
PHP
É necessário usar o PHP SDK 2.7.0 ou posterior.
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to the endpoint of the region where the bucket is located. In this example, the endpoint of the China (Hangzhou) region is used.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.jpg. The full path cannot contain the bucket name.
$object = "src.jpg";
// Specify the full path of the local file. Example: D:\\localpath\\example-new.jpg. If the specified local file exists, it is overwritten. Otherwise, a new file is created.
// If you specify only the local file name (for example, example-new.jpg) without a local path, the file is saved to the local path of the project by default.
$download_file = "D:\\dest.jpg";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
// Specify the general-purpose Alibaba Cloud region ID.
"region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Apply a blur to the image with a radius of 10 and a standard deviation of 10.
$image = "image/blur,r_10,s_10";
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => $image);
// Save the processed image to your local machine.
$ossClient->getObject($bucket, $object, $options);
Python
É necessário usar o Python SDK 2.18.4 ou posterior.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set yourEndpoint to the endpoint of the region where the bucket is located. In this example, the endpoint of the China (Hangzhou) region is used.
# Specify the endpoint of the region where the bucket is located. In this example, the endpoint of the China (Hangzhou) region is used.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the general-purpose Alibaba Cloud region ID.
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)
# Specify the name of the source image. If the image is not in the root directory of the bucket, specify the full path of the image, such as exampledir/example.jpg.
key = 'src.jpg'
# Specify the name of the processed image.
new_pic = 'D:\\dest.jpg'
# Apply a blur to the image with a radius of 10 and a standard deviation of 10.
image = 'image/blur,r_10,s_10'
bucket.get_object_to_file(key, new_pic, process=image)
Go
É necessário usar o Go SDK 3.0.2 ou posterior.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func HandleError(err error) {
fmt.Println("Error:", err)
os.Exit(-1)
}
func main() {
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Set yourEndpoint to the endpoint of the bucket. In this example, the endpoint of the China (Hangzhou) region is used. Replace it with the actual endpoint.
client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
if err != nil {
HandleError(err)
}
// Specify the name of the bucket where the source image is stored. Example: examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
}
// Specify the name of the source image. If the image is not in the root directory of the bucket, specify the full path of the image, such as exampledir/example.jpg.
sourceImageName := "src.jpg"
// Specify the name of the processed image.
targetImageName := "D://dest.jpg"
// Apply a blur to the image with a radius of 10 and a standard deviation of 10.
image := "image/blur,r_10,s_10"
err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
if err != nil {
HandleError(err)
}
}
Usar uma API REST
Se o seu aplicativo exigir um alto grau de personalização, faça solicitações diretamente à API REST. Para isso, é necessário escrever manualmente o código para calcular a assinatura. Para obter mais informações sobre como calcular o cabeçalho de solicitação Authorization, consulte Assinatura da versão 4 (recomendada).
Adicione parâmetros de desfoque à operação GetObject para processar uma imagem. Para obter mais informações, consulte GetObject.
GET /oss.jpg?x-oss-process=image/blur,r_10,s_10 HTTP/1.1
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValue
Imagens privadas (requer vinculação a um projeto IMM)
Para usar os parâmetros g_face ou g_faces, primeiro vincule o bucket a um projeto do Intelligent Media Management (IMM). Para obter mais informações, consulte Início rápido.
Usar um SDK do Alibaba Cloud
Os exemplos de código a seguir mostram como adicionar um efeito de desfoque a imagens privadas com SDKs comuns. Para exemplos com outros SDKs, consulte Visão geral do SDK.
Java
É necessário usar o Java SDK 3.17.4 ou posterior.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;
public class Demo {
public static void main(String[] args) throws Throwable {
// In this example, the endpoint of the China (Hangzhou) region is used. Replace it with the actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region that corresponds to the endpoint. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the source image. The full path cannot contain the bucket name.
String objectName = "example.jpg";
// Specify the full path to which you want to save the processed image. Example: D:\\dest.jpg. If the specified local file exists, it is overwritten. Otherwise, a new file is created.
String pathName = "D:\\dest.jpg";
// Create an OSSClient instance.
// When the OSSClient instance is no longer used, call the shutdown method to release the resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Set the blur scope to all faces, and apply a blur with a radius of 25 and a standard deviation of 50.
String image = "image/blur,g_faces,r_25,s_50";
GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
request.setProcess(image);
// Save the processed image to your local machine.
// If you specify only the file name (for example, dest.jpg) without a local path, the file is saved to the local path of the project by default.
ossClient.getObject(request, new File("D:\\dest.jpg"));
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
PHP
É necessário usar o PHP SDK 2.7.0 ou posterior.
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to the endpoint of the region where the bucket is located. In this example, the endpoint of the China (Hangzhou) region is used.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the source image. The full path cannot contain the bucket name.
$object = "src.jpg";
// Specify the full path to which you want to save the processed image. Example: D:\\dest.jpg. If the specified local file exists, it is overwritten. Otherwise, a new file is created.
// If you specify only the local file name (for example, dest.jpg) without a local path, the file is saved to the local path of the project by default.
$download_file = "D:\\dest.jpg";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
// Specify the general-purpose Alibaba Cloud region ID.
"region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Set the blur scope to all faces, and apply a blur with a radius of 25 and a standard deviation of 50.
$image = "image/blur,g_faces,r_25,s_50";
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => $image);
// Save the processed image to your local machine.
$ossClient->getObject($bucket, $object, $options);
Python
É necessário usar o Python SDK 2.18.4 ou posterior.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region where the bucket is located. In this example, the endpoint of the China (Hangzhou) region is used.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the general-purpose Alibaba Cloud region ID.
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)
# If the source image is in the root directory of the bucket, specify only the image name, such as source-example.jpg. If the source image is not in the root directory, specify the full path, such as exampledir/source-example.jpg.
key = 'source-example.jpg'
# Specify the full path of the local file. Example: D:\\target-example.jpg. If the specified local file exists, it is overwritten. Otherwise, a new file is created.
local_file_name = 'D:\\target-example.jpg'
# Set the blur scope to all faces, and apply a blur with a radius of 25 and a standard deviation of 50.
process = 'image/blur,g_faces,r_25,s_50'
# Use the get_object method and pass the processing instruction in the process parameter.
result = bucket.get_object_to_file(key, local_file_name, process=process)
Go
É necessário usar o Go SDK 3.0.2 ou posterior.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func HandleError(err error) {
fmt.Println("Error:", err)
os.Exit(-1)
}
func main() {
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Set yourEndpoint to the endpoint of the bucket. In this example, the endpoint of the China (Hangzhou) region is used. Replace it with the actual endpoint.
client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
if err != nil {
HandleError(err)
}
// Specify the name of the bucket where the source image is stored. Example: examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
}
// Specify the name of the source image. If the image is not in the root directory of the bucket, specify the full path of the image, such as exampledir/example.jpg.
sourceImageName := "example.jpg"
// Specify the name of the processed image.
targetImageName := "D://dest.jpg"
// Set the blur scope to all faces, and apply a blur with a radius of 25 and a standard deviation of 50.
image := "image/blur,g_faces,r_25,s_50"
err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
if err != nil {
HandleError(err)
}
}
Usar uma API REST
Se o seu aplicativo exigir um alto grau de personalização, faça solicitações diretamente à API REST. Para isso, é necessário escrever manualmente o código para calcular a assinatura. Para obter mais informações sobre como calcular o cabeçalho de solicitação Authorization, consulte Assinatura da versão 4 (recomendada).
Adicione parâmetros de desfoque à operação GetObject para processar uma imagem. Para obter mais informações, consulte GetObject.
GET /oss.jpg?x-oss-process=image/blur,g_faces,r_25,s_50 HTTP/1.1
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValue
Parâmetros
Ação: blur
A tabela a seguir descreve os parâmetros.
|
Parâmetro |
Obrigatório |
Descrição |
Valores válidos |
|
r |
Sim |
O raio de desfoque. |
[1, 50] Quanto maior o valor, maior o desfoque da imagem. |
|
s |
Sim |
O desvio padrão da distribuição normal. |
[1, 50] Quanto maior o valor, maior o desfoque da imagem. |
|
g |
Não |
O escopo do desfoque. |
Nota
|
|
p |
Não |
O fator de escala. |
[1, 200] Unidade: porcentagem. Nota
Este parâmetro só é eficaz quando g_face ou g_faces estiver definido. |
Exemplos
Desfocar uma imagem inteira
Desfocar o maior rosto
Desfocar todos os rostos
Desfocar o maior rosto e redimensionar a área desfocada para 200%
Desfocar todos os rostos e definir uma área ampliada em 2x
Referências
Aplique operações de processamento de imagem diretamente na URL de uma imagem. Também é possível usar Cascading Style Sheets (CSS) para ajustar ainda mais o estilo e otimizar o efeito visual. O código a seguir mostra como usar o recurso de processamento de imagem do OSS para desfocar uma imagem e combiná-la com CSS para um efeito visual mais rico.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blur Effect Example</title>
<style>
.blurred {
filter: blur(5px);
}
.container {
position: relative;
width: 300px;
}
.text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 24px;
}
</style>
</head>
<body>
<div class="container">
<img src="https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg" alt="Sample Image" class="blurred">
<div class="text">Hello World</div>
</div>
<div>
<img src="https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg?x-oss-process=image%2Fblur%2Cr_10%2Cs_10&spm=a2c4g.11186623.0.i12">
</div>
</body>
</html>





