Jersey——返回图片格式数据

本文介绍了如何在使用Jersey构建Restful后端时,不仅返回JSON格式数据,还能返回图片流。通过Spring Boot和Jersey搭建示例,详细阐述了三种返回图片流的方法:直接返回byte[]数组、BufferedImage对象和InputStream对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、背景
在使用Jersey实现Restful后端设计的时候,Jersey常用用于返回JSON格式数据,实际上Jersey是可以返回其他格式的数据的,在MVC中与Springmvc都是可以做为C的,由于项目上需要通过Jersey实现返回图片流的接口,为简单起见现采用springboot+jersey搭建示例环境。

二、操作步骤

  1. 使用Spring initializer创建,引入springboot和jersey,生成的配置文件如下:
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>
  1. 对于返回图片流有三种方式:
    a) 直接放回byte[]数组:
	@GET
	@Path("")
	@Consumes("image/*")
	@Produces("image/png")
	public Response getImage() {
		final File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\7a04373d04277b26de8e7397ea5a9d46.jpg");
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			StreamUtils.copy(new FileInputStream(file), bos);
			return Response.ok(bos.toByteArray()).build();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

b) 直接返回BufferedImage对象

    @Path("2")
    @GET
    @Consumes("image/*")
    @Produces("image/*")
    public Response getImage2() {
        final File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\7a04373d04277b26de8e7397ea5a9d46.jpg");
        try {
            BufferedImage bufferedImage = ImageIO.read(file);
            return Response.ok(bufferedImage, "image/png").build();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

c) 直接返回InputStream对象

	@GET
    @Path("3")
    @Consumes("image/*")
    @Produces("image/png")
    public Response getImage4() {
        final File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\7a04373d04277b26de8e7397ea5a9d46.jpg");
        try {
            return Response.ok(new FileInputStream(file)).build();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

三、参考链接

  1. Spring Boot Jersey Example
  2. How to return a PNG image from Jersey REST service method to the browser
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值