如何通过Plumber提供已保存的图片文件服务?
Serving Local Saved Images with Plumber
No worries, serving pre-saved local images with Plumber is totally doable—here are two reliable approaches depending on your needs:
1. Single Image Endpoint (For Specific Images)
If you want to expose individual images through dedicated endpoints, you can read the image file as raw binary data and return it with the correct content type header.
Here's a complete example script:
# Save as local_image_server.R library(plumber) #* Serve a pre-saved PNG plot #* @get /my-plot #* @serializer contentType list(type="image/png") function() { # Replace this with your actual image file path img_path <- "./my_saved_plot.png" # Add a quick check to avoid errors if the file doesn't exist if (!file.exists(img_path)) { stop("Image file not found at the specified path!") } # Read the file as raw binary and return it readBin(img_path, "raw", file.info(img_path)$size) } #* Serve a pre-saved JPG photo #* @get /my-photo #* @serializer contentType list(type="image/jpeg") function() { img_path <- "./vacation_photo.jpg" if (!file.exists(img_path)) { stop("Image file not found!") } readBin(img_path, "raw", file.info(img_path)$size) }
How to use it:
- Replace the
img_pathvalues with your actual local image paths - Run the server:
pr <- plumber::plumb("local_image_server.R") pr$run(port=8000) - Visit
http://localhost:8000/my-plotorhttp://localhost:8000/my-photoin your browser to see the images.
2. Static File Directory (For Multiple Images)
If you have a folder full of images and want to serve all of them without writing individual endpoints, use Plumber's static file serving feature. This lets you access any file in a specified directory via a URL path.
Update your script to include static file mounting:
# Save as static_image_server.R library(plumber) # Optional: Add custom endpoints if needed (like the ones above) # Mount a directory of static files (images in this case) pr <- plumb("static_image_server.R") # Replace "./my_images_folder" with your actual directory path pr$mount("/static", PlumberStatic$new("./my_images_folder/")) pr$run(port=8000)
How to use it:
- Put all your images in the
my_images_folderdirectory (or whatever path you specify) - Run the server, then access images via
http://localhost:8000/static/[your-image-filename]—for example:http://localhost:8000/static/plot1.pnghttp://localhost:8000/static/photo2.jpg
Important Notes:
- Make sure the Plumber process has read permissions for the image files/directory
- Double-check file paths (relative paths are relative to where you run the Plumber script from)
- Use the correct content type for your image:
image/pngfor PNGs,image/jpegfor JPG/JPEGs,image/giffor GIFs, etc.
内容的提问来源于stack exchange,提问作者OganM
相关产品推荐
相关产品推荐

