获取响应图像作为Base64

huangapple go评论85阅读模式
英文:

Get response image as Base64

问题

我有一个链接,响应是一张图片。

我想使用 apache-httpclient,将这张图片获取为 base64。

以下是我写的代码:

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

    HttpGet httpGet = new HttpGet("...");

    try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {

        int code = httpResponse.getStatusLine().getStatusCode();
        String body = EntityUtils.toString(httpResponse.getEntity());

        if (code == HttpStatus.SC_OK) {

            System.out.print(body); //返回奇怪的字符 ⍁
            return;

        }

        String reason = httpResponse.getStatusLine().getReasonPhrase();
        throw new Exception("错误 - 代码:" + code + " - 原因:" + reason + " - 响应内容:" + body);

    }

} catch (Exception e) {
    e.printStackTrace();
}

这个 EntityUtils.toString(httpResponse.getEntity()); 不太好。它只返回了一堆 ⍁。

我该如何将图片获取为 base64?

我尝试了

Base64.getEncoder().encodeToString(EntityUtils.toString(httpResponse.getEntity()).getBytes());

但结果表示一个无效的图片。

测试用的链接: https://i.stack.imgur.com/jRsnt.jpg - 我在处理这个链接时遇到问题。

英文:

I have a link which gives as response an image.

I want, with apache-httpclient, to get this image as base64.

This is what I wrote:

try(CloseableHttpClient httpClient = HttpClients.createDefault()){

	HttpGet httpGet = new HttpGet("...");

    try(CloseableHttpResponse httpResponse = httpClient.execute(httpGet)){

        int code = httpResponse.getStatusLine().getStatusCode();
		String body = EntityUtils.toString(httpResponse.getEntity());

		if(code == HttpStatus.SC_OK){

			System.out.print(body); //returns weird chars ⍁
            return;

		}

        String reason = httpResponse.getStatusLine().getReasonPhrase();
		throw new Exception("Error - code: " + code + " - reason: " + reason + " - body: " + body);

    }

}catch (Exception e){
	e.printStackTrace();
}

This EntityUtils.toString(httpResponse.getEntity()); is not good. It returns just a bunch of ⍁.

How I can get the image as base64?

I tried

Base64.getEncoder().encodeToString(EntityUtils.toString(httpResponse.getEntity()).getBytes());

but the result represent an invalid image.

URL for test: https://i.stack.imgur.com/jRsnt.jpg - with this one I have problems.

答案1

得分: 1

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    HttpGet httpGet = new HttpGet("https://i.imgur.com/sIm1gSs.jpg");
    try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
        int code = httpResponse.getStatusLine().getStatusCode();
        
        // 从httpclient获取流,需要将其转换为字节数组
        // 我们将使用ByteArrayOutputStream
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        httpResponse.getEntity().writeTo(byteArrayOutputStream);    // 写入ByteArrayStream

        String body = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());

        if (code == HttpStatus.SC_OK) {
            System.out.print(body); // 返回有效的Base64图片
            return;
        }

        String reason = httpResponse.getStatusLine().getReasonPhrase();
        throw new Exception("错误 - 代码:" + code + " - 原因:" + reason + " - 正文:" + body);
    }
} catch (Exception e) {
    e.printStackTrace();
}
英文:

You need to convert received Stream (from HTTPClient entity class) to byte array.
I made some minor tweaks to your code and it works fine now (returns a valid base64 representation of image)

try(CloseableHttpClient httpClient = HttpClients.createDefault()){

            HttpGet httpGet = new HttpGet("https://i.imgur.com/sIm1gSs.jpg");

            try(CloseableHttpResponse httpResponse = httpClient.execute(httpGet)){

                int code = httpResponse.getStatusLine().getStatusCode();
                
                // You are getting stream from httpclient. It needs to be converted to byte array
                // We will use byteArrayOutputStream. 
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                httpResponse.getEntity().writeTo(byteArrayOutputStream);    // Writing to ByteArrayStream

                String body = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());

                if(code == HttpStatus.SC_OK){

                    System.out.print(body); //returns valid Base64 image
                    return;

                }

                String reason = httpResponse.getStatusLine().getReasonPhrase();
                throw new Exception("Error - code: " + code + " - reason: " + reason + " - body: " + body);

            }

        }catch (Exception e){
            e.printStackTrace();
        }

答案2

得分: 0

我找到了将图像转换为Base64的方法:

BufferedImage bufferedImage = ImageIO.read(httpResponse.getEntity().getContent());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
String body = Base64.getEncoder().encodeToString(imageInByte);
英文:

I found the way to get the image as base64:

BufferedImage bufferedImage = ImageIO.read(httpResponse.getEntity().getContent());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
String body = Base64.getEncoder().encodeToString(imageInByte);

huangapple
  • 本文由 发表于 2020年10月4日 20:03:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/64194365.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定