您现在的位置是:首页 > 正文

使用 Unsplash API 生成随机图片

2023-05-13 09:48:15阅读 248
## **Unsplash** ![](https://gulimall-com-mall.oss-cn-hangzhou.aliyuncs.com/688714352634834945.jpg) 如果你想使用免费版权的图片时,无论你是否用于商业用途,[Unsplash](https://unsplash.com/) 是不错的选择。 我自己也经常用它来制作大型背景图片,例如:[https://www.youhang.site](https://www.imyangyong.com/) 。 虽然他们为开发人员提供了很棒的 API,但他们也提供了通过 URL 访问随机图片的选项。 ## **1\. 默认随机** 请看这个例子,从他们巨大的存储中生成随机的图片。 ```css https://source.unsplash.com/random ``` ## **指定用户** 我们还可以从特定用户账号中生成随机图像。URL 格式是这样的: ```css https://source.unsplash.com/user/{USERNAME} ``` 你可以尝试单击下面的链接,从我的账号中随机生成图片: [https://source.unsplash.com/user/angusyang9/likes](https://source.unsplash.com/user/angusyang9/likes) ## **3\. 指定尺寸** 还有一个选项可以设置要生成的图像的大小。像这样: ```css https://source.unsplash.com/random/{WIDTH}x{HEIGHT} ``` 让我们生成下 300 x 300 大小的图片: [https://source.unsplash.com/random/300×300](https://source.unsplash.com/random/300%C3%97300) ## **4\. 依据关键词搜索** 这个真的很棒。你可以从搜索词生成图像。让我们搜索下城市和夜晚(非常有创意): [https://source.unsplash.com/random/?city,night](https://source.unsplash.com/random/?city,night) 当然,你可以与尺寸配合使用: [https://source.unsplash.com/random/900×700/?fruit](https://source.unsplash.com/random/900%C3%97700/?fruit) ## **代码示例** 以下是 react 中的代码片段: ```css class RandomImg extends React.Component { constructor() { super(); this.state = { bgImageUrl: require('./default.jpeg') } } componentDidMount() { this.generateImage(); } generateImage(){ fetch(`https://source.unsplash.com/random/?people`).then((response) => { preloadImage(response.url); }) } preloadImage(url) { let img = new Image(); img.src = url; img.onload = () => { this.setState({ bgImageUrl: url }); } } render() { return <img src={bgImageUrl} /> } } ``` 参考: * [Generate Random Images From Unsplash Without Using The API](https://awik.io/generate-random-images-unsplash-without-using-api/)

网站文章