Java常用工具类---image图片处理工具类、Json工具类

package com.jarvis.base.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import net.coobird.thumbnailator.Thumbnails;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 *   
 * 
 * @Title: ImageHelper.java
 * @Package com.jarvis.base.util
 * @Description:图片处理工具类。
 * @version V1.0  
 */
@SuppressWarnings("restriction")
public class ImageHelper {
	/**
	 * @描述:Base64解码并生成图片
	 * @入参:@param imgStr
	 * @入参:@param imgFile
	 * @入参:@throws IOException
	 * @出参:void
	 */
	public static void generateImage(String imgStr, String imgFile) throws IOException {
		BASE64Decoder decoder = new BASE64Decoder();
		// Base64解码
		byte[] bytes;
		OutputStream out = null;
		try {
			bytes = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
			// 生成图片
			out = new FileOutputStream(imgFile);
			out.write(bytes);
			out.flush();
		} catch (IOException e) {
			throw new IOException();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * @throws IOException
	 * @描述:根据路径得到base编码后图片
	 * @入参:@param imgFilePath
	 * @入参:@return
	 * @出参:String
	 */
	public static String getImageStr(String imgFilePath) throws IOException {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
		byte[] data = null;

		// 读取图片字节数组
		try {
			InputStream in = new FileInputStream(imgFilePath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException
  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里给出一个 Java 版本的图片审核工具类,同样使用了百度的内容审核 API。 注意,这里需要使用到百度的 API Key 和 Secret Key,请根据自己的实际情况进行替换。 ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.*; public class ImageModeration { private String apiKey; private String secretKey; private String accessToken; public ImageModeration(String apiKey, String secretKey) { this.apiKey = apiKey; this.secretKey = secretKey; this.accessToken = getAccessToken(); } private String getAccessToken() { String accessTokenUrl = "https://aip.baidubce.com/oauth/2.0/token"; Map<String, String> params = new HashMap<>(); params.put("grant_type", "client_credentials"); params.put("client_id", apiKey); params.put("client_secret", secretKey); try { String result = HttpUtil.post(accessTokenUrl, params); return JsonUtil.getValue(result, "access_token"); } catch (Exception e) { e.printStackTrace(); return null; } } public JSONObject imageModeration(String imagePath, String imageType, String[] scenes, double threshold) { String image = imageToBase64(imagePath); String url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined"; Map<String, String> params = new HashMap<>(); params.put("image", image); params.put("image_type", imageType); params.put("scenes", String.join(",", scenes)); params.put("threshold", String.valueOf(threshold)); try { String result = HttpUtil.post(url, params, accessToken); return new JSONObject(result); } catch (Exception e) { e.printStackTrace(); return null; } } private String imageToBase64(String imagePath) { File file = new File(imagePath); try (InputStream in = new FileInputStream(file)) { byte[] data = new byte[in.available()]; in.read(data); return Base64.getEncoder().encodeToString(data); } catch (IOException e) { e.printStackTrace(); return null; } } } class HttpUtil { public static String post(String url, Map<String, String> params) throws Exception { return post(url, params, null); } public static String post(String url, Map<String, String> params, String accessToken) throws Exception { HttpURLConnection conn = null; BufferedReader reader = null; try { URL realUrl = new URL(url); conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (accessToken != null) { conn.setRequestProperty("Authorization", "Bearer " + accessToken); } conn.setDoOutput(true); conn.setDoInput(true); OutputStream out = conn.getOutputStream(); out.write(getParamString(params).getBytes()); out.flush(); out.close(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } return result.toString(); } finally { if (reader != null) { reader.close(); } if (conn != null) { conn.disconnect(); } } } private static String getParamString(Map<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); result.append("&"); } return result.substring(0, result.length() - 1); } } class JsonUtil { public static String getValue(String json, String key) throws JSONException { JSONObject object = new JSONObject(json); return object.getString(key); } } ``` 该工具类的使用方法如下: ```java String apiKey = "your_api_key"; String secretKey = "your_secret_key"; ImageModeration moderation = new ImageModeration(apiKey, secretKey); JSONObject result = moderation.imageModeration("your_image_path", "BASE64", new String[]{"antiporn"}, 0.95); System.out.println(result); ``` 其中,`apiKey` 和 `secretKey` 分别为你的百度 API Key 和 Secret Key,`your_image_path` 为待审核的图片路径。`imageModeration` 方法的返回值是一个 `JSONObject` 对象,包含了审核结果的详细信息。你可以根据需要对这些信息进行解析和处理

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值