You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

调用Unsplash API获取指定尺寸图片失败求助

Fixing Unsplash API Random Photo Size Issue

Hey there! I’ve run into this exact problem before when building a service that needed consistent image sizes from Unsplash. Let’s break down what’s likely going wrong and how to fix it:

Common Mistakes & Solutions

1. You’re using the wrong URL from the API response

When you call the /photos/random endpoint with w=300 and h=500, the API returns metadata including multiple image URLs (like urls.small, urls.regular, urls.raw). The w and h parameters only affect the urls.raw link—if you’re using any other URL (like regular), you’ll get the default size for that preset.

Fix: Extract the urls.raw value from the API response, and that will include your specified dimensions. For example, the raw URL will look like:
https://images.unsplash.com/photo-123456...?w=300&h=500&fm=jpg&crop=entropy&cs=tinysrgb

2. Missing the fit parameter (optional but critical for consistency)

By default, Unsplash might adjust the size to maintain the original aspect ratio, which can result in images that don’t match your exact w/h if the ratio is different. Adding the fit parameter ensures the image is resized exactly to your specs:

  • fit=crop: Crops the image to fit your dimensions (great for consistent aspect ratios)
  • fit=max: Resizes the image to fit within your dimensions without cropping (may leave empty space if ratio differs)

Example Request:
GET /photos/random?client_id=YOUR_API_KEY&w=300&h=500&fit=crop

3. Directly requesting the image URL (alternative approach)

If you don’t need the full photo metadata, you can skip the /photos/random endpoint entirely and directly request a sized image. Use this format:
https://images.unsplash.com/random?w=300&h=500&fit=crop
This will return a random photo exactly at your specified dimensions, no extra metadata needed.

4. Double-check parameter spelling & placement

Make sure you’re using lowercase w and h (not width/height), and that the parameters are correctly appended as query strings (not in the path). A common typo is mixing up h and w, which would give you a tall image instead of wide, or vice versa.

Quick Code Snippet Example (JavaScript)

If you’re using fetch, here’s how to get the correctly sized image:

fetch('https://api.unsplash.com/photos/random?client_id=YOUR_KEY&w=300&h=500&fit=crop')
  .then(res => res.json())
  .then(data => {
    // Use the raw URL for your taxi image
    const taxiImageUrl = data.urls.raw;
    console.log('Sized image URL:', taxiImageUrl);
  })
  .catch(err => console.error('Error:', err));

Just remember to replace YOUR_KEY with your actual Unsplash API client ID, and you should start getting consistent 300x500 images for your taxi listings!

内容的提问来源于stack exchange,提问作者Vid

火山引擎 最新活动