react 图像识别
React is a good tool when it comes to building flexible and reusable UI components. However, it's "one of those libraries" that cannot handle all the tasks involved in building a full fleshed UI project. Other supporting tools - such as a recently announced ReactJS SDK from Cloudinary - are available to provide solutions that the React core cannot.
在构建灵活且可重用的UI组件时, React是一个很好的工具。 但是,它是“那些库之一”,无法处理构建完整的UI项目所涉及的所有任务。 其它支持工具-如最近宣布ReactJS SDK从Cloudinary -可用来提供解决方案,该阵营的核心不能。
In such cases where media (images and videos) becomes a heavy task to handle, Cloudinary simplifies the process with the new React SDK. Let's build and image library with Cloudinary and React using the Cloudinary's React SDK.
在媒体(图像和视频)成为繁重的任务要处理的情况下, Cloudinary使用新的React SDK简化了流程。 让我们使用Cloudinary的React SDK使用Cloudinary和React构建和映像库。
先决条件 ( Prerequisites )
The only requirements for using Cloudinary in your existing React project are to install the React SDK and the upload widget. If you do not have an existing React project and want to try these examples, take the following steps:
在现有React项目中使用Cloudinary的唯一要求是安装React SDK和上载小部件。 如果您没有现有的React项目,并且想尝试这些示例,请执行以下步骤:
1.安装依赖项 (1. Install Dependencies)
We need a minimal amount of dependencies so we can focus on building a media library and not structuring a React app:
我们需要最少的依赖关系,因此我们可以专注于构建媒体库而不是构建React应用程序:
{
"name": "img-library",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "webpack -d --watch",
"build": "webpack",
"serve": "serve ./public"
},
"author": "",
"license": "MIT",
"devDependencies": {
"babel-core": "^6.18.2",
"babel-loader": "^6.2.9",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"serve": "^1.4.0",
"webpack": "^1.14.0"
},
"dependencies": {
"axios": "^0.15.3",
"cloudinary-react": "^1.0.1",
"react": "^15.4.1",
"react-dom": "^15.4.1"
}
}
React (and React DOM) must be used since we are making a React app. The cloudinary-react
dependency is Cloudinary's React SDK, which we will soon see how it works. axios
is a tool for making HTTP requests and, in our case, we will use it request images from the Cloudinary server.
由于我们正在制作React应用,因此必须使用React(和React DOM)。 cloudinary-react
依赖关系是Cloudinary的React SDK,我们将很快看到它的工作原理。 axios
是用于发出HTTP请求的工具,在本例中,我们将使用它从Cloudinary服务器请求图像。
# Install dependencies
npm install
2.设置Webpack (2. Setup Webpack)
Webpack is our build tool. Only minimal settings are required to have a build running and our React app compiling:
Webpack是我们的构建工具。 运行构建和编译我们的React应用程序只需要最少的设置:
// ./webpack.config.js
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'public');
var APP_DIR = path.resolve(__dirname, 'src');
var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module : {
loaders : [
{
test : /\.jsx?/,
include : APP_DIR,
loader : 'babel'
}
]
}
};
module.exports = config;
Basic configuration - an entry, output and loaders to handle the React .jsx
files.
基本配置-处理React .jsx
文件的入口,输出和加载器。
3.入口点 (3. Entry Points)
We need to create an entry point, as we specified in the Webpack configuration, and another entry point for the browser, which is an index.html
file:
我们需要创建一个入口点(如我们在Webpack配置中指定的那样),并为浏览器创建另一个入口点,即index.html
文件:
// ./src/index.jsx
import React, { Component } from 'react';
import { render } from 'react-dom';
class Main extends Component {
render() {
return (
<div className="main">
<h1>Scotchage</h1>
</div>
);
}
}
render(<Main />, document.getElementById('container'));
<!-- ./public/index.html -->
<html>
<head>
<!--Stylesheet-->
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!--Container for React rendering-->
<div id="container"></div>
<!--Bundled file-->
<script src="bundle.js"></script>
</body>
</html>
4.创建Cloudinary帐户 (4. Create Cloudinary Account)
You need a Cloudinary account to continue with these examples. Sign up for free and store your credentials safely as shown on the dashboard:
您需要一个Cloudinary帐户才能继续执行这些示例。 免费注册并安全地存储您的凭据,如仪表板上所示:
上传图片 ( Uploading Images )
Before using the React SDK to deliver images from the Cloudinary servers, let's use the awesome Cloudinary upload widget to upload images. First, we need to add this widget to our index.html
:
在使用React SDK从Cloudinary服务器传送图像之前,让我们使用很棒的Cloudinary上传小部件来上传图像。 首先,我们需要将此小部件添加到我们的index.html
:
<!-- ./public/index.html -->
<html>
<head>
. . .
</head>
<body>
. . .
<!-- UPLOAD WIDGET -->
<script src="//widget.cloudinary.com/global/all.js" type="text/javascript"></script>
<script src="bundle.js"></script>
</body>
</html>
Next, we create a button, attach an event to it and upload an image once the button is clicked:
接下来,我们创建一个按钮,向其添加事件,并在单击按钮后上传图像:
import React, { Component } from 'react';
import { render } from 'react-dom';
class Main extends Component {
uploadWidget() {
cloudinary.openUploadWidget({ cloud_name: 'CLOUD_NAME', upload_preset: 'PRESET', tags:['xmas']},
function(error, result) {
console.log(result);
});
}
render(){
return (
<div className="main">
<h1>Galleria</h1>
<div className="upload">
<button onClick={this.uploadWidget.bind(this)} className="upload-button">
Add Image
</button>
</div>
</div>
);
}
}
render(<Main />, document.getElementById('container'));
The uploadWidget
member method is the handler invoked by the click event to handle our image upload by calling cloudinary.openUploadWidget
. openUploadWidget
takes a config object and the upload callback handler. The config object must have at least cloud_name
and upload_preset
properties with valid values. You can read more about Cloud Names and Upload Presets.
uploadWidget
成员方法是click事件调用的处理程序,通过调用cloudinary.openUploadWidget
来处理我们的图像上传。 openUploadWidget
需要一个配置对象和上载回调处理程序。 config对象必须至少具有有效值的cloud_name
和upload_preset
属性。 您可以阅读有关云名称和上传预设的更多信息。
使用SDK交付图像 ( Delivering Images with SDK )
The Cloudinary React SDK has three major components, Image
, CloudinaryContext
and Transformation
:
Cloudinary React SDK具有三个主要组件, Image
, CloudinaryContext
和Transformation
:
- Image: This component is responsible for the actual delivery of images. It takes the image ID and asks the server for this image. When the image is provided, it is also responsible for painting the image on the browser. 图像 :此组件负责图像的实际交付。 它获取图像ID,并向服务器询问该图像。 提供图像后,它还负责在浏览器上绘制图像。
- Transformation: This component is used to apply transformations to images delivered with
Image
. 转换 :此组件用于将转换应用于随Image
交付的Image
。 - CloudinaryContext: You can specify Cloudinary configuration for each image on the
Image
component. This can be tedious when you are dealing with multiple images.CloudinaryContext
allows you to apply configuration to a group ofImage
s. CloudinaryContext :您可以为Image
组件上的每个图像指定Cloudinary配置。 当您处理多个图像时,这可能很乏味。CloudinaryContext
允许您将配置应用于一组Image
。
Most times you would end up with a structure like this:
大多数情况下,您最终会得到如下结构:
<CloudinaryContext>
<Image>
<Transformation />
<Transformation />
</Image>
<Image>
<Transformation />
</Image>
</CloudinaryContext>
Back to our demo app, we can request an image from the Cloudinary server and display it with the following components:
返回我们的演示应用程序,我们可以从Cloudinary服务器请求一个图像,并将其与以下组件一起显示:
import React, { Component } from 'react';
import axios from 'axios';
import { CloudinaryContext, Transformation, Image } from 'cloudinary-react';
import { render } from 'react-dom';
class Main extends Component {
constructor(props) {
super(props);
this.state = {
gallery: []
}
}
componentDidMount() {
// Request for images tagged xmas
axios.get('http://res.cloudinary.com/christekh/image/list/xmas.json')
.then(res => {
console.log(res.data.resources);
this.setState({gallery: res.data.resources});
});
}
uploadWidget() {
// . . .
}
render(){
return (
<div className="main">
<h1>Galleria</h1>
<div className="gallery">
<CloudinaryContext cloudName="CLOUDNAME">
{
this.state.gallery.map(data => {
return (
<div className="responsive" key={data.public_id}>
<div className="img">
<a target="_blank" href={`http://res.cloudinary.com/christekh/image/upload/${data.public_id}.jpg`}>
<Image publicId={data.public_id}>
<Transformation
crop="scale"
width="300"
height="200"
dpr="auto"
responsive_placeholder="blank"
/>
</Image>
</a>
<div className="desc">Created at {data.created_at}</div>
</div>
</div>
)
})
}
</CloudinaryContext>
<div className="clearfix"></div>
</div>
</div>
);
}
}
render(<Main />, document.getElementById('container'));
Take one more look at the upload code:
再看一下上传代码:
cloudinary.openUploadWidget({ cloud_name: 'christekh', upload_preset: 'idcidr0h', tags:['xmas']},
function(error, result) {
. . .
Each image is tagged with xmas
, which serves as a way to request images with this tag as a collection. This is exactly what we are using the axios
library to do when the component mounts:
每个图像都标记有xmas
,这是一种请求使用此标签作为集合的图像的方法。 当组件挂载时,这正是我们使用axios
库执行的操作:
axios.get('http://res.cloudinary.com/CLOUDNAME/image/list/xmas.json')
.then(res => {
console.log(res.data.resources);
this.setState({gallery: res.data.resources});
});
axios
uses promises, so whenever the promise resolves in our case, we have a payload of images. We take advantage of React state to update our UI with the fetched resources.
axios
使用promise,因此在我们的情况下,只要promise axios
解决,我们就会拥有图像的有效负载。 我们利用React状态来利用获取的资源更新我们的UI。
Down to rendering, we configure the CloudinaryContext
with our cloud_name
, iterate over the gallery
state that stores the images and displays them using the Image
component. We also apply few transformations using the Transformation
component.
一直到渲染,我们使用CloudinaryContext
配置cloud_name
,遍历存储图像的gallery
状态并使用Image
组件显示它们。 我们还使用“ Transformation
组件应用了很少的Transformation
。
For security reasons, Cloudinary will not allow you to make such request from the client unless you tell it to. The best way to go is to use the admin API via a backend SDK and then send the resource list to the client.
出于安全原因,除非您告知 ,Cloudinary不允许您从客户端发出此类请求。 最好的方法是通过后端SDK使用admin API,然后将资源列表发送到客户端。
使用新上传的内容更新状态 ( Updating State with New Uploads )
We are able to upload images and request for images to be displayed on the user's browsers. Here is how we update the displayed images instantly when the user uploads a new image:
我们能够上传图像,并要求将图像显示在用户的浏览器中。 这是我们在用户上传新图像时立即更新显示图像的方法:
uploadWidget() {
let _this = this;
cloudinary.openUploadWidget({ cloud_name: 'CLOUDNAME', upload_preset: 'PRESET', tags:['xmas']},
function(error, result) {
// Update gallery state with newly uploaded image
_this.setState({gallery: _this.state.gallery.concat(result)})
});
}
Rather than logging the uploaded image information to the console, we update the gallery
state, which bears the list of requested images, by concatenating the uploaded result to the gallery
.
通过将上传的结果连接到gallery
,我们更新了带请求图像列表的gallery
状态,而不是将上传的图像信息记录到控制台。
简化影像管理 ( Image Management Simplified )
Image uploads, transformation and delivery has never been easier. These tasks have been a serious challenge for developers. Cloudinary has created a way to abstract all this hard work, enabling you to simply plug and play.
图像上传,转换和交付从未如此简单。 这些任务对开发人员来说是一个严峻的挑战。 Cloudinary创建了一种抽象所有艰苦工作的方法,使您可以即插即用。
This content is sponsored via Syndicate Ads.
此内容是通过Syndicate Ads赞助的。
翻译自: https://scotch.io/tutorials/leveraging-react-for-easy-image-management-with-cloudinary
react 图像识别