图片处理:html文本获取图片Url,判断图片大小,存数据库

前端开发   发布日期:2025年06月05日   浏览次数:141

1.从html文本获取图片Url

  1. /**
  2. * html文本中取出url链接
  3. */
  4. public class Url {
  5. public static void main(String[] args) {
  6. String content="<div><img src='123.jpg'/>ufiolk<img src='456.jpg'/></div>";
  7. List<String> imgUrls = parseImg(content);
  8. for (String imgUrl : imgUrls) {
  9. System.out.println(imgUrl);
  10. }
  11. }
  12. public static List<String> parseImg(String content){
  13. Element doc = Jsoup.parseBodyFragment(content).body();
  14. Elements elements = doc.select("img[src]");
  15. List<String> imgUrls = new ArrayList<>(elements == null ? 1 : elements.size());
  16. for (Element element : elements) {
  17. String imgUrl = element.attr("src");
  18. if(StringUtils.isNotBlank(imgUrl)){
  19. imgUrls.add(imgUrl);
  20. }
  21. }
  22. return imgUrls;
  23. }
  24. }

2.判断图片大小,格式

 

  1. public class Url {
  2. public static void main(String[] args) {
  3. boolean b = checkImageSize(new File("C:\\Users\\吕厚厚\\Pictures\\Warframe\\wallhaven-760559 (1).png"), 1 * 1024L);
  4. System.out.println(b);
  5. }
  6. /**
  7. * 校验图片的大小
  8. * @param file 文件
  9. * @param imageSize 图片最大值(KB)
  10. * @return true:上传图片小于图片的最大值
  11. */
  12. public static boolean checkImageSize(File file, Long imageSize) {
  13. if (!file.exists()) {
  14. return false;
  15. }
  16. System.out.println("file.length:"+ file.length());
  17. Long size = file.length() / 1024; // 图片大小(得到的是字节数,需除以1024,转化为KB)
  18. System.out.println("size:"+size);
  19. Long maxImageSize = null;
  20. if (maxImageSize == null) {
  21. maxImageSize = 2 * 1024L;// 图片最大不能超过2M(2048kb)
  22. } else {
  23. maxImageSize = maxImageSize * 1024;
  24. }
  25. if (size > maxImageSize) {
  26. return false;
  27. }
  28. if (imageSize == null) {
  29. return true;
  30. }
  31. if (size.intValue() <= imageSize) {
  32. return true;
  33. }
  34. return false;
  35. }
  36. //根据文件名判断图片是否为要求的格式
  37. public static boolean checkImageType(String fileFullname){
  38. //获取图片扩展名
  39. String type = fileFullname.substring(fileFullname.lastIndexOf(".") + 1);
  40. //判断是否为要求的格式
  41. if (type == "bmp" || type == "jpg" || type == "jpeg" || type == "gif" || type == "JPG" || type == "JPEG" || type == "BMP" || type == "GIF") {
  42. return true;
  43. }
  44. return false;
  45. }
  46. }

根据流判断图片类型

  1. //测试根据文件流判断图片类型
  2. @Test
  3. public void judgeImageType(){
  4. PicVO pic = weixinReleaseMaterialDao.getPic("a00394c9-4db4-43c6-adc7-d7d3019624ed");
  5. if(pic==null||pic.getBinaryPic()==null){
  6. throw new RuntimeException("从数据库取出二进制数据的字节数组为空");
  7. }
  8. byte[] binaryPic =pic.getBinaryPic();
  9. String picType = getPicType(binaryPic);
  10. System.out.println("pic____"+picType);
  11. }
  12. /**
  13. * 根据文件流判断图片类型
  14. * @param
  15. * @return jpg/png/gif/bmp
  16. */
  17. public static String getPicType(byte[] src) {
  18. StringBuilder stringBuilder = new StringBuilder();
  19. if (src == null || src.length <= 0) {
  20. return null;
  21. }
  22. for (int i = 0; i < 4; i++) {
  23. int v = src[i] & 0xFF;
  24. String hv = Integer.toHexString(v);
  25. if (hv.length() < 2) {
  26. stringBuilder.append(0);
  27. }
  28. stringBuilder.append(hv);
  29. }
  30. String type = stringBuilder.toString().toUpperCase();
  31. if (type.contains("FFD8FF")) {
  32. return IMG_JPG;
  33. } else if (type.contains("89504E47")) {
  34. return IMG_PNG;
  35. } else if (type.contains("47494638")) {
  36. return IMG_GIF;
  37. } else if (type.contains("424D")) {
  38. return IMG_BMP;
  39. }else{
  40. return "";
  41. }
  42. }

 

3. 根据URL下载图片

 

  1. public class Url {
  2. public static void main(String[] args) {
  3. /*String content="<div><img src='123.jpg'/>ufiolk<img src='456.jpg'/></div>";
  4. List<String> imgUrls = parseImg(content);
  5. for (String imgUrl : imgUrls) {
  6. System.out.println(imgUrl);
  7. }*/
  8. /*boolean b = checkImageSize(new File("C:\\Users\\吕厚厚\\Pictures\\Warframe\\wallhaven-760559 (1).png"), 1 * 1024L);
  9. System.out.println(b);*/
  10. //根据url下载图片
  11. String imgUrl="https://pics4.baidu.com/feed/a8014c086e061d950b35770c91eacad462d9cab3.jpeg?token=c41d6d4d1b4c59af07a9bfc2b874b245&s=702A955598FECFCC341BFCEF0300E038";
  12. InputStream inputStream = downloadImgByUrl(imgUrl);
  13. try {
  14. byte[] s = IOUtils.toByteArray(inputStream);//byte数组接收
  15. System.out.println(s);
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. public static InputStream downloadImgByUrl(String imageUrl) {
  21. InputStream inputStream = null;
  22. inputStream = ImgUtils.getByUrl(imageUrl);//通过url下载并得到输入流
  23. if (null == inputStream) {
  24. throw new RuntimeException("下载文件出错,输入流为空");
  25. }
  26. return inputStream;
  27. }

 

 

3.存图片到数据库

数据类型选择:

BLOB类型的字段用于存储二进制数据

MySQL中,BLOB是个类型系列,包括:TinyBlob、Blob、MediumBlob、LongBlob,这几个类型之间的唯一区别是在存储文件的最大大小上不同。

MySQL的四种BLOB类型
类型 大小(单位:字节)
TinyBlob 最大 255
Blob 最大 65K
MediumBlob 最大 16M
LongBlob 最大 4G

从数据库查出图片:

直接查出表里的整个对象,避免byte[]  不知道对应的resultType的问题。

  1. /**Mybatis3.0
  2. *Dao层
  3. * @param picId
  4. * @return
  5. */
  6. public PicVO getPic(String picId){
  7. Map<String, Object> param = new HashMap<>();
  8. param.put("picId", picId);
  9. return super.selectOne(apperNameSpace .concat("queryPic"),param);
  10. }
  11. <!--查询二进制图片-->
  12. <select >
  13. select ID ,PIC_ID ,BINARY_PIC
  14. from zycf_mediaoperate_pics
  15. where 1=1
  16. <if test="picId!=null">
  17. and PIC_ID=#{picId,jdbcType=VARCHAR}
  18. </if>
  19. </select>
  20. <resultMap >
  21. <result column="ID" jdbcType="VARCHAR" property="id"/>
  22. <result column="PIC_ID" jdbcType="VARCHAR" property="picId"/>
  23. <result column="BINARY_PIC" property="binaryPic" jdbcType="LONGVARBINARY" />
  24. </resultMap>

4.形成图片文件

  1. //根据图片id从数据库取出二进制数据
  2. String[] split = StringUtils.split(articlePicsId,",");
  3. if(split==null||split.length==0){
  4. //throw new RuntimeException("split__为空");
  5. }
  6. for (int i = 0; i <split.length ; i++) {
  7. PicVO pic = weixinReleaseMaterialDao.getPic(split[i]);
  8. if(pic==null||pic.getBinaryPic()==null){
  9. //throw new RuntimeException("从数据库取出二进制数据的字节数组为空");
  10. }
  11. byte[] binaryPic =pic.getBinaryPic();
  12. //转为图片文件
  13. File image = getImage(binaryPic);
  14. //字节数组转为图片文件
  15. private static File getImage(byte[] bytes){
  16. try {
  17. String tmpRootPath;
  18. String tmp = System.getProperty("java.io.tmpdir");
  19. if(tmp.endsWith(File.separator)){
  20. tmpRootPath = tmp;
  21. }else{
  22. tmpRootPath = tmp.concat(File.separator);
  23. }
  24. ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
  25. File jpgfile = new File(tmpRootPath.concat("123.jpg"));
  26. FileUtils.copyInputStreamToFile(bais, jpgfile);
  27. /* BufferedImage bi1 = ImageIO.read(bais);
  28. //String tempPath = PropertiesUtil.getProperty("trs-config.properties","mailTempDir");
  29. // 文件名
  30. File w2 = new File("C:\\Users\\吕厚厚\\Pictures\\Warframe", "123.jpg");// 可以是jpg,png,gif格式
  31. ImageIO.write(bi1, "jpg", w2);// 不管输出什么格式图片,此处不需改动
  32. */
  33. return jpgfile;
  34. } catch (IOException e) {
  35. e.getMessage();
  36. e.printStackTrace();
  37. }
  38. return null;
  39. }

 

5.图片上传

  1. //利用HttpPostUtil
  2.      
  3.  HttpPostUtil u = new HttpPostUtil(requestUrl);
  4. u.addFileParameter("img", new File(filePath));
  5. //发送数据到服务器,解析返回数据
  6. JSONObject result = JSONObject.parseObject(new String(u.send()));
  1. HttpPostUtil
  1. import javax.imageio.ImageIO;
  2. import javax.imageio.ImageReader;
  3. import javax.imageio.stream.ImageInputStream;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.DataOutputStream;
  6. import java.io.File;
  7. import java.io.FileInputStream;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.net.HttpURLConnection;
  11. import java.net.SocketTimeoutException;
  12. import java.net.URL;
  13. import java.net.URLEncoder;
  14. import java.util.HashMap;
  15. import java.util.Iterator;
  16. import java.util.Map;
  17. import java.util.Set;
  18. public class HttpPostUtil {
  19. URL url;
  20. HttpURLConnection conn;
  21. String boundary = "--------httppost123";
  22. Map<String, String> textParams = new HashMap<String, String>();
  23. Map<String, File> fileparams = new HashMap<String, File>();
  24. DataOutputStream ds;
  25. public HttpPostUtil(String url) throws Exception {
  26. this.url = new URL(url);
  27. }
  28. //重新设置要请求的服务器地址,即上传文件的地址。
  29. public void setUrl(String url) throws Exception {
  30. this.url = new URL(url);
  31. }
  32. //增加一个普通字符串数据到form表单数据中
  33. public void addTextParameter(String name, String value) {
  34. textParams.put(name, value);
  35. }
  36. //增加一个文件到form表单数据中
  37. public void addFileParameter(String name, File value) {
  38. fileparams.put(name, value);
  39. }
  40. // 发送数据到服务器,返回一个字节包含服务器的返回结果的数组
  41. public byte[] send() throws Exception {
  42. initConnection();
  43. try {
  44. conn.connect();
  45. } catch (SocketTimeoutException e) {
  46. // something
  47. throw new RuntimeException();
  48. }
  49. ds = new DataOutputStream(conn.getOutputStream());
  50. writeFileParams();
  51. writeStringParams();
  52. paramsEnd();
  53. InputStream in = conn.getInputStream();
  54. ByteArrayOutputStream out = new ByteArrayOutputStream();
  55. int b;
  56. while ((b = in.read()) != -1) {
  57. out.write(b);
  58. }
  59. conn.disconnect();
  60. return out.toByteArray();
  61. }
  62. //文件上传的connection的一些必须设置
  63. private void initConnection() throws Exception {
  64. conn = (HttpURLConnection) this.url.openConnection();
  65. conn.setDoOutput(true);
  66. conn.setUseCaches(false);
  67. conn.setConnectTimeout(10000); //连接超时为10秒
  68. conn.setRequestMethod("POST");
  69. conn.setRequestProperty("Content-Type",
  70. "multipart/form-data; boundary=" + boundary);
  71. }
  72. //普通字符串数据
  73. private void writeStringParams() throws Exception {
  74. Set<String> keySet = textParams.keySet();
  75. for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
  76. String name = it.next();
  77. String value = textParams.get(name);
  78. ds.writeBytes("--" + boundary + "\r\n");
  79. ds.writeBytes("Content-Disposition: form-data; name=\"" + name
  80. + "\"\r\n");
  81. ds.writeBytes("\r\n");
  82. ds.writeBytes(encode(value) + "\r\n");
  83. }
  84. }
  85. //文件数据
  86. private void writeFileParams() throws Exception {
  87. Set<String> keySet = fileparams.keySet();
  88. for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
  89. //update-begin-author:taoYan date:20180601 for:文件加入http请求,当文件非本地资源的时候需要作特殊处理--
  90. String name = it.next();
  91. File value = fileparams.get(name);
  92. String valuename = value.getName();
  93. if(value.exists()){
  94. ds.writeBytes("--" + boundary + "\r\n");
  95. ds.writeBytes("Content-Disposition: form-data; name=\"" + name
  96. + "\"; filename=\"" + encode(valuename) + "\"\r\n");
  97. ds.writeBytes("Content-Type: " + getContentType(value) + "\r\n");
  98. ds.writeBytes("\r\n");
  99. ds.write(getBytes(value));
  100. }else{
  101. String myFilePath = value.getPath();
  102. if(myFilePath!=null && myFilePath.startsWith("http")){
  103. byte[] netFileBytes = getURIFileBytes(myFilePath);
  104. String lowerValueName = valuename.toLowerCase();
  105. if(lowerValueName.endsWith(IMG_BMP)||lowerValueName.endsWith(IMG_GIF)||lowerValueName.endsWith(IMG_JPG)||lowerValueName.endsWith(IMG_PNG)){
  106. valuename = encode(valuename);
  107. }else{
  108. valuename = System.currentTimeMillis()+getPicType(netFileBytes);
  109. }
  110. ds.writeBytes("--" + boundary + "\r\n");
  111. ds.writeBytes("Content-Disposition: form-data; name=\"" + name
  112. + "\"; filename=\"" + valuename + "\"\r\n");
  113. ds.writeBytes("Content-Type: " + getContentType(value) + "\r\n");
  114. ds.writeBytes("\r\n");
  115. ds.write(netFileBytes);
  116. }
  117. }
  118. //update-end-author:taoYan date:20180601 for:文件加入http请求,当文件非本地资源的时候需要作特殊处理--
  119. ds.writeBytes("\r\n");
  120. }
  121. }
  122. /**
  123. * 通过文件的网络地址转化成流再读到字节数组中去
  124. */
  125. private byte[] getURIFileBytes(String url) throws IOException{
  126. url = url.replace("http:"+File.separator,"http://").replace("\\","/");
  127. URL oracle = new URL(url);
  128. InputStream inStream = oracle.openStream();
  129. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  130. byte[] buffer = new byte[1024];
  131. int len = 0;
  132. while ((len = inStream.read(buffer)) != -1) {
  133. outStream.write(buffer, 0, len);
  134. }
  135. inStream.close();
  136. return outStream.toByteArray();
  137. }
  138. //获取文件的上传类型,图片格式为image/png,image/jpg等。非图片为application/octet-stream
  139. private String getContentType(File f) throws Exception {
  140. // return "application/octet-stream"; // 此行不再细分是否为图片,全部作为application/octet-stream 类型
  141. ImageInputStream imagein = ImageIO.createImageInputStream(f);
  142. if (imagein == null) {
  143. return "application/octet-stream";
  144. }
  145. Iterator<ImageReader> it = ImageIO.getImageReaders(imagein);
  146. if (!it.hasNext()) {
  147. imagein.close();
  148. return "application/octet-stream";
  149. }
  150. imagein.close();
  151. return "image/" + it.next().getFormatName().toLowerCase();//将FormatName返回的值转换成小写,默认为大写
  152. }
  153. //把文件转换成字节数组
  154. private byte[] getBytes(File f) throws Exception {
  155. FileInputStream in = new FileInputStream(f);
  156. ByteArrayOutputStream out = new ByteArrayOutputStream();
  157. byte[] b = new byte[1024];
  158. int n;
  159. while ((n = in.read(b)) != -1) {
  160. out.write(b, 0, n);
  161. }
  162. in.close();
  163. return out.toByteArray();
  164. }
  165. //添加结尾数据
  166. private void paramsEnd() throws Exception {
  167. ds.writeBytes("--" + boundary + "--" + "\r\n");
  168. ds.writeBytes("\r\n");
  169. }
  170. // 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码
  171. private String encode(String value) throws Exception{
  172. return URLEncoder.encode(value, "UTF-8");
  173. }
  174. //update-begin-author:taoYan date:20180601 for:增加图片类型常量--
  175. public static final String IMG_JPG = ".jpg";
  176. public static final String IMG_PNG = ".png";
  177. public static final String IMG_GIF = ".gif";
  178. public static final String IMG_BMP = ".bmp";
  179. /**
  180. * 根据文件流判断图片类型
  181. * @param
  182. * @return jpg/png/gif/bmp
  183. */
  184. public String getPicType(byte[] src) {
  185. StringBuilder stringBuilder = new StringBuilder();
  186. if (src == null || src.length <= 0) {
  187. return null;
  188. }
  189. for (int i = 0; i < 4; i++) {
  190. int v = src[i] & 0xFF;
  191. String hv = Integer.toHexString(v);
  192. if (hv.length() < 2) {
  193. stringBuilder.append(0);
  194. }
  195. stringBuilder.append(hv);
  196. }
  197. String type = stringBuilder.toString().toUpperCase();
  198. if (type.contains("FFD8FF")) {
  199. return IMG_JPG;
  200. } else if (type.contains("89504E47")) {
  201. return IMG_PNG;
  202. } else if (type.contains("47494638")) {
  203. return IMG_GIF;
  204. } else if (type.contains("424D")) {
  205. return IMG_BMP;
  206. }else{
  207. return "";
  208. }
  209. }
  210. //update-end-author:taoYan date:20180601 for:根据文件流判断图片类型--
  211. public static void main(String[] args) throws Exception {
  212. HttpPostUtil u = new HttpPostUtil("https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=i3um002Np_n-mgNVbPP9JEIfft7_hRq3eHE86slxI7Uh_5q0K5rFfLRnhD20HTCcFt92ulWnndpGlyiNgXi6UiWQqKxPCBsfYKmiY6Ws-isUVLaAFAXYO");
  213. u.addFileParameter("img", new File("C:/Users/zhangdaihao/Desktop/2.png"));
  214. byte[] b = u.send();
  215. String result = new String(b);
  216. System.out.println(result);
  217. }
  218. }

以上就是图片处理:html文本获取图片Url,判断图片大小,存数据库的详细内容,更多关于图片处理:html文本获取图片Url,判断图片大小,存数据库的资料请关注九品源码其它相关文章!