1.从html文本获取图片Url

/**
* html文本中取出url链接
*/
public class Url {
public static void main(String[] args) {
String content="<div><img src='123.jpg'/>ufiolk<img src='456.jpg'/></div>";
List<String> imgUrls = parseImg(content);
for (String imgUrl : imgUrls) {
System.out.println(imgUrl);
} }
public static List<String> parseImg(String content){
Element doc = Jsoup.parseBodyFragment(content).body();
Elements elements = doc.select("img[src]");
List<String> imgUrls = new ArrayList<>(elements == null ? 1 : elements.size());
for (Element element : elements) {
String imgUrl = element.attr("src");
if(StringUtils.isNotBlank(imgUrl)){
imgUrls.add(imgUrl);
}
}
return imgUrls;
}
}

2.判断图片大小,格式

public class Url {
public static void main(String[] args) { boolean b = checkImageSize(new File("C:\\Users\\吕厚厚\\Pictures\\Warframe\\wallhaven-760559 (1).png"), 1 * 1024L);
System.out.println(b);
} /**
* 校验图片的大小
* @param file 文件
* @param imageSize 图片最大值(KB)
* @return true:上传图片小于图片的最大值
*/
public static boolean checkImageSize(File file, Long imageSize) {
if (!file.exists()) {
return false;
}
System.out.println("file.length:"+ file.length());
Long size = file.length() / 1024; // 图片大小(得到的是字节数,需除以1024,转化为KB)
System.out.println("size:"+size);
Long maxImageSize = null;
if (maxImageSize == null) {
maxImageSize = 2 * 1024L;// 图片最大不能超过2M(2048kb)
} else {
maxImageSize = maxImageSize * 1024;
}
if (size > maxImageSize) {
return false;
}
if (imageSize == null) {
return true;
}
if (size.intValue() <= imageSize) {
return true;
}
return false;
}
//根据文件名判断图片是否为要求的格式
public static boolean checkImageType(String fileFullname){
//获取图片扩展名
String type = fileFullname.substring(fileFullname.lastIndexOf(".") + 1);
//判断是否为要求的格式
if (type == "bmp" || type == "jpg" || type == "jpeg" || type == "gif" || type == "JPG" || type == "JPEG" || type == "BMP" || type == "GIF") {
return true;
}
return false;
}
}

根据流判断图片类型

//测试根据文件流判断图片类型
@Test
public void judgeImageType(){
PicVO pic = weixinReleaseMaterialDao.getPic("a00394c9-4db4-43c6-adc7-d7d3019624ed");
if(pic==null||pic.getBinaryPic()==null){
throw new RuntimeException("从数据库取出二进制数据的字节数组为空");
}
byte[] binaryPic =pic.getBinaryPic();
String picType = getPicType(binaryPic);
System.out.println("pic____"+picType);
}
/**
* 根据文件流判断图片类型
* @param
* @return jpg/png/gif/bmp
*/
public static String getPicType(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < 4; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
String type = stringBuilder.toString().toUpperCase();
if (type.contains("FFD8FF")) {
return IMG_JPG;
} else if (type.contains("89504E47")) {
return IMG_PNG;
} else if (type.contains("47494638")) {
return IMG_GIF;
} else if (type.contains("424D")) {
return IMG_BMP;
}else{
return "";
}
}

3. 根据URL下载图片

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

3.存图片到数据库

数据类型选择:

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

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

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

从数据库查出图片:

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

 /**Mybatis3.0
*Dao层
* @param picId
* @return
*/
public PicVO getPic(String picId){
Map<String, Object> param = new HashMap<>();
param.put("picId", picId);
return super.selectOne(apperNameSpace .concat("queryPic"),param);
} <!--查询二进制图片-->
<select id="queryPic" resultMap="picMap" parameterType="java.util.Map">
select ID ,PIC_ID ,BINARY_PIC
from zycf_mediaoperate_pics
where 1=1
<if test="picId!=null">
and PIC_ID=#{picId,jdbcType=VARCHAR}
</if>
</select> <resultMap id="picMap" type="Bean.PicVO">
<result column="ID" jdbcType="VARCHAR" property="id"/>
<result column="PIC_ID" jdbcType="VARCHAR" property="picId"/>
<result column="BINARY_PIC" property="binaryPic" jdbcType="LONGVARBINARY" />
</resultMap>

4.形成图片文件

 //根据图片id从数据库取出二进制数据

                    String[] split = StringUtils.split(articlePicsId,",");

                    if(split==null||split.length==0){
//throw new RuntimeException("split__为空");
} for (int i = 0; i <split.length ; i++) { PicVO pic = weixinReleaseMaterialDao.getPic(split[i]); if(pic==null||pic.getBinaryPic()==null){
//throw new RuntimeException("从数据库取出二进制数据的字节数组为空");
}
byte[] binaryPic =pic.getBinaryPic(); //转为图片文件
File image = getImage(binaryPic); //字节数组转为图片文件
private static File getImage(byte[] bytes){
try {
String tmpRootPath;
String tmp = System.getProperty("java.io.tmpdir");
if(tmp.endsWith(File.separator)){
tmpRootPath = tmp;
}else{
tmpRootPath = tmp.concat(File.separator);
}
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
File jpgfile = new File(tmpRootPath.concat("123.jpg"));
FileUtils.copyInputStreamToFile(bais, jpgfile);
/* BufferedImage bi1 = ImageIO.read(bais);
//String tempPath = PropertiesUtil.getProperty("trs-config.properties","mailTempDir");
// 文件名
File w2 = new File("C:\\Users\\吕厚厚\\Pictures\\Warframe", "123.jpg");// 可以是jpg,png,gif格式
ImageIO.write(bi1, "jpg", w2);// 不管输出什么格式图片,此处不需改动
*/
return jpgfile;
} catch (IOException e) {
e.getMessage();
e.printStackTrace();
}
return null;
}

5.图片上传

//利用HttpPostUtil
     
 HttpPostUtil u = new HttpPostUtil(requestUrl);
u.addFileParameter("img", new File(filePath));
//发送数据到服务器,解析返回数据
JSONObject result = JSONObject.parseObject(new String(u.send()));
HttpPostUtil:
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set; public class HttpPostUtil {
URL url;
HttpURLConnection conn;
String boundary = "--------httppost123";
Map<String, String> textParams = new HashMap<String, String>();
Map<String, File> fileparams = new HashMap<String, File>();
DataOutputStream ds; public HttpPostUtil(String url) throws Exception {
this.url = new URL(url);
}
//重新设置要请求的服务器地址,即上传文件的地址。
public void setUrl(String url) throws Exception {
this.url = new URL(url);
}
//增加一个普通字符串数据到form表单数据中
public void addTextParameter(String name, String value) {
textParams.put(name, value);
}
//增加一个文件到form表单数据中
public void addFileParameter(String name, File value) {
fileparams.put(name, value);
} // 发送数据到服务器,返回一个字节包含服务器的返回结果的数组
public byte[] send() throws Exception {
initConnection();
try {
conn.connect();
} catch (SocketTimeoutException e) {
// something
throw new RuntimeException();
}
ds = new DataOutputStream(conn.getOutputStream());
writeFileParams();
writeStringParams();
paramsEnd();
InputStream in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
conn.disconnect();
return out.toByteArray();
}
//文件上传的connection的一些必须设置
private void initConnection() throws Exception {
conn = (HttpURLConnection) this.url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(10000); //连接超时为10秒
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
}
//普通字符串数据
private void writeStringParams() throws Exception {
Set<String> keySet = textParams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
String value = textParams.get(name);
ds.writeBytes("--" + boundary + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\"" + name
+ "\"\r\n");
ds.writeBytes("\r\n");
ds.writeBytes(encode(value) + "\r\n");
}
}
//文件数据
private void writeFileParams() throws Exception {
Set<String> keySet = fileparams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
//update-begin-author:taoYan date:20180601 for:文件加入http请求,当文件非本地资源的时候需要作特殊处理--
String name = it.next();
File value = fileparams.get(name);
String valuename = value.getName();
if(value.exists()){
ds.writeBytes("--" + boundary + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\"" + name
+ "\"; filename=\"" + encode(valuename) + "\"\r\n");
ds.writeBytes("Content-Type: " + getContentType(value) + "\r\n");
ds.writeBytes("\r\n");
ds.write(getBytes(value));
}else{
String myFilePath = value.getPath();
if(myFilePath!=null && myFilePath.startsWith("http")){
byte[] netFileBytes = getURIFileBytes(myFilePath);
String lowerValueName = valuename.toLowerCase();
if(lowerValueName.endsWith(IMG_BMP)||lowerValueName.endsWith(IMG_GIF)||lowerValueName.endsWith(IMG_JPG)||lowerValueName.endsWith(IMG_PNG)){
valuename = encode(valuename);
}else{
valuename = System.currentTimeMillis()+getPicType(netFileBytes);
}
ds.writeBytes("--" + boundary + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\"" + name
+ "\"; filename=\"" + valuename + "\"\r\n");
ds.writeBytes("Content-Type: " + getContentType(value) + "\r\n");
ds.writeBytes("\r\n");
ds.write(netFileBytes);
}
}
//update-end-author:taoYan date:20180601 for:文件加入http请求,当文件非本地资源的时候需要作特殊处理--
ds.writeBytes("\r\n");
}
} /**
* 通过文件的网络地址转化成流再读到字节数组中去
*/
private byte[] getURIFileBytes(String url) throws IOException{
url = url.replace("http:"+File.separator,"http://").replace("\\","/");
URL oracle = new URL(url);
InputStream inStream = oracle.openStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
} //获取文件的上传类型,图片格式为image/png,image/jpg等。非图片为application/octet-stream
private String getContentType(File f) throws Exception { // return "application/octet-stream"; // 此行不再细分是否为图片,全部作为application/octet-stream 类型
ImageInputStream imagein = ImageIO.createImageInputStream(f);
if (imagein == null) {
return "application/octet-stream";
}
Iterator<ImageReader> it = ImageIO.getImageReaders(imagein);
if (!it.hasNext()) {
imagein.close();
return "application/octet-stream";
}
imagein.close();
return "image/" + it.next().getFormatName().toLowerCase();//将FormatName返回的值转换成小写,默认为大写 }
//把文件转换成字节数组
private byte[] getBytes(File f) throws Exception {
FileInputStream in = new FileInputStream(f);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
}
in.close();
return out.toByteArray();
}
//添加结尾数据
private void paramsEnd() throws Exception {
ds.writeBytes("--" + boundary + "--" + "\r\n");
ds.writeBytes("\r\n");
}
// 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码
private String encode(String value) throws Exception{
return URLEncoder.encode(value, "UTF-8");
} //update-begin-author:taoYan date:20180601 for:增加图片类型常量--
public static final String IMG_JPG = ".jpg";
public static final String IMG_PNG = ".png";
public static final String IMG_GIF = ".gif";
public static final String IMG_BMP = ".bmp";
/**
* 根据文件流判断图片类型
* @param
* @return jpg/png/gif/bmp
*/
public String getPicType(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < 4; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
String type = stringBuilder.toString().toUpperCase();
if (type.contains("FFD8FF")) {
return IMG_JPG;
} else if (type.contains("89504E47")) {
return IMG_PNG;
} else if (type.contains("47494638")) {
return IMG_GIF;
} else if (type.contains("424D")) {
return IMG_BMP;
}else{
return "";
}
}
//update-end-author:taoYan date:20180601 for:根据文件流判断图片类型-- public static void main(String[] args) throws Exception {
HttpPostUtil u = new HttpPostUtil("https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=i3um002Np_n-mgNVbPP9JEIfft7_hRq3eHE86slxI7Uh_5q0K5rFfLRnhD20HTCcFt92ulWnndpGlyiNgXi6UiWQqKxPCBsfYKmiY6Ws-isUVLaAFAXYO");
u.addFileParameter("img", new File("C:/Users/zhangdaihao/Desktop/2.png"));
byte[] b = u.send();
String result = new String(b);
System.out.println(result); } }

图片处理:html文本获取图片Url,判断图片大小,存数据库的更多相关文章

  1. 从url下载图片--java与python实现方式比较

    从url下载图片--java与python实现方式比较 博客分类: 技术笔记小点滴 javapython图片下载  一.java的实现方式 首先读取图片 //方式一:直接根据url读取图片 priva ...

  2. (java)Jsoup爬虫学习--获取网页所有的图片,链接和其他信息,并检查url和文本信息

    Jsoup爬虫学习--获取网页所有的图片,链接和其他信息,并检查url和文本信息 此例将页面图片和url全部输出,重点不太明确,可根据自己的需要输出和截取: import org.jsoup.Jsou ...

  3. Android开发之异步获取并下载网络资源-下载图片和下载文本内容

    在android网络开发过程中,经常需要获取网络资源,比如下载图片,下载文本文件内容等,这个时候就需要http请求来获取相应的网络资源.首先看看实例效果图:              下载图片截图   ...

  4. C# 网络编程之webBrowser获取网页url和下载网页中图片

    该文章主要是通过C#网络编程的webBrowser获取网页中的url并简单的尝试瞎子啊网页中的图片,主要是为以后网络开发的基础学习.其中主要的通过应用程序结合网页知识.正则表达式实现浏览.获取url. ...

  5. 011_如何decode url及图片转为base64文本编码总结

    一.咱们经常会遇到浏览器给encode后的url,如何转换成咱们都能识别的url呢?很简单,talk is easy,Please show me your code,如下所示: (1)英文decod ...

  6. 正则表达式 获取字符串内提取图片URL字符串

    #region 获取字符串内提取图片URL字符串 /// <summary> /// 获取字符串内提取图片URL字符串 /// </summary> /// <param ...

  7. js判断图片加载完成后获取图片实际宽高

    通常,我们会用jq的.width()/.height()方法获取图片的宽度/高度或者用js的.offsetwidth/.offsetheight方法来获取图片的宽度/高度,但这些方法在我们通过样式设置 ...

  8. 上传图片用图片文件的对象hash哈希值判断图片是否一样,避免重复提交相同的图片到服务器中

    上传图片用图片文件的对象hash哈希值判断图片是否一样,避免重复提交相同的图片到服务器中 前端:要用到一个插件,点击下载 <!DOCTYPE html> <html xmlns=&q ...

  9. php 判断图片类型

    脚本之家 <?php $imgurl = "http://www.jb51.net/images/logo.gif"; //方法1 echo $ext = strrchr($ ...

随机推荐

  1. js 验证手机号

    <script> var reg = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/; function ver ...

  2. 数据挖掘经典算法PrefixSpan的一个简单Python实现

    前言 用python实现了一个没有库依赖的"纯" py-based PrefixSpan算法. Github 仓库 https://github.com/Holy-Shine/Pr ...

  3. linux c基础技巧

    C语言:向文件末尾进行追加数据https://blog.csdn.net/qq_31243065/article/details/82354557 https://zhidao.baidu.com/q ...

  4. jenkins publish .net core application to linux server

    最近学习Docker与Jenkins, 网上大部分都是关于Jenkins+Git+Docker进行持续远程部署, 我一直在考虑为什么Jenkins和Docker要绑定一块使用, 因为我想单独使用Jen ...

  5. Python 常用包收集

    转自:http://www.cnblogs.com/Logic0/archive/2010/09/03/1850382.html 常用的自带类库 常用的外部类库       Tkinter———— P ...

  6. PHP如何访问数据库集群

    一般常见的有三种做法, 1,自动判断sql是否为读,来选择数据库的连接: 实例化php DB类的时候,需要一次连接两台服务器,然后根据slq选择不同的连接,举个例子: $link_w = mysql_ ...

  7. LeetCode 171. Excel表列序号(Excel Sheet Column Number) 22

    171. Excel表列序号 171. Excel Sheet Column Number 题目描述 给定一个 Excel 表格中的列名称,返回其相应的列序号. 每日一算法2019/5/25Day 2 ...

  8. [转帖]单集群10万节点 走进腾讯云分布式调度系统VStation

    单集群10万节点 走进腾讯云分布式调度系统VStation https://www.sohu.com/a/227223696_355140 2018-04-04 08:18 云计算并非无中生有的概念, ...

  9. Python-20-异常处理

    一.什么是异常 异常就是程序运行时发生错误的信号(在程序出现错误时,则会产生一个异常,若程序没有处理它,则会抛出该异常,程序的运行也随之终止) 常用异常: AttributeError 试图访问一个对 ...

  10. Python-18-类的内置属性

    1. __getattr__.set__attr__.__delattr__ class Foo: x=1 def __init__(self,y): self.y=y def __getattr__ ...