简单,向MySql中存入图片

5 篇文章 0 订阅

学习JavaWeb的时候,接触到了mysql,想到向表中存放图片,那今后照片管理就可以用sql语句来执行了,所以尝试了一下,试错过程还挺长的。

1.效果

在这里插入图片描述
不是存了个字符串哈,可以看左边的数据类型。

2. 获取blob数据

我们创建一个方法使用FileInputStream读取图片,还有ByteArrayOutputStream将读取的数据写入byte[]数组,然后

public static byte[] getImgStr(String path) throws IOException {
        FileInputStream fis = new FileInputStream(path);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int len = 0;
        byte[] b = new byte[1024];
        while ((len = fis.read(b))!= -1){
            out.write(b,0,len);
        }

        //接收out
        byte[] array = out.toByteArray();
        fis.close();
        out.close();

        return array;
    }

3.连接数据库并写入sql语句

使用Blob创建一个Blob,然后将我们获取的图片数据转换成blob类型,然后用PreparedStatement执行sql语句,因为它支持占位符并且有setBlob方法可以直接将我们的blob地址中的值写入数据库。然后就大功告成了。

    public static void main(String[] args) {
        /*
        加载驱动
         */
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取连接
            String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
            String user= "root";
            String password ="123456";
            try {
                Connection connection = DriverManager.getConnection(url,user,password);

                /*
                插入图片
                 */
                byte[] arr = getImgStr("图片地址");
                Blob blob = connection.createBlob();
                blob.setBytes(1,arr);

                String sql = "insert into pictures (name,pic,date) values('张三',?,'2015-01-01')";

                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setBlob(1,blob);
                ps.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }

    }
  • 12
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要使用Scrapy爬取图片并将其存储到MySQL,需要遵循以下步骤: 1. 在Scrapy项目创建一个MySQL数据库连接。(可以使用PyMySQL库) 2. 创建一个Item类来存储图像链接和图像标题等信息。 3. 在spider使用XPath或CSS选择器来提取图像链接和标题等信息,并通过Item将其传递给pipelines。 4. 在pipelines,使用requests库下载图像并将其存储到本地文件系统。 5. 然后使用Python的MySQL库将图像路径和其他相关信息插入到MySQL数据库。 以下是一个简单的示例代码: ```python import scrapy from scrapy.pipelines.images import ImagesPipeline from scrapy.exceptions import DropItem import pymysql from PIL import Image class MySQLPipeline(object): def __init__(self, db_host, db_port, db_user, db_password, db_name): self.db_host = db_host self.db_port = db_port self.db_user = db_user self.db_password = db_password self.db_name = db_name self.conn = None self.cursor = None @classmethod def from_crawler(cls, crawler): return cls( db_host=crawler.settings.get('DB_HOST'), db_port=crawler.settings.get('DB_PORT'), db_user=crawler.settings.get('DB_USER'), db_password=crawler.settings.get('DB_PASSWORD'), db_name=crawler.settings.get('DB_NAME'), ) def open_spider(self, spider): self.conn = pymysql.connect( host=self.db_host, port=self.db_port, user=self.db_user, password=self.db_password, db=self.db_name, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) self.cursor = self.conn.cursor() def close_spider(self, spider): self.conn.close() def process_item(self, item, spider): try: # 将图片下载到本地 image_path = item['image_urls'][0] image_title = item['title'] image_extension = image_path.split('.')[-1] image_name = f'{image_title}.{image_extension}' image_path = image_path.replace('thumb180', 'large') image_request = scrapy.Request(image_path) image_response = scrapy.utils.python.get_val_from_func( image_request, 'response', spider=spider ) image_content = image_response.body image = Image.open(BytesIO(image_content)) image.save(f'{image_name}', quality=95) # 将图片信息插入到数据库 sql = "INSERT INTO images (title, path) VALUES (%s, %s)" self.cursor.execute(sql, (image_title, image_name)) self.conn.commit() except Exception as e: print(e) raise DropItem(f"Error processing item: {item['image_urls']}") ``` 在Scrapy的settings.py文件需要添加以下配置: ```python ITEM_PIPELINES = { 'scrapy.pipelines.images.ImagesPipeline': 1, 'myproject.pipelines.MySQLPipeline': 2, } IMAGES_STORE = '/path/to/your/images/folder' DB_HOST = 'localhost' DB_PORT = 3306 DB_USER = 'root' DB_PASSWORD = 'password' DB_NAME = 'database_name' ``` 在spider需要使用ImageItem来存储图像链接和标题等信息: ```python from scrapy import Spider from myproject.items import ImageItem class MySpider(Spider): name = 'myspider' start_urls = ['http://example.com'] def parse(self, response): image_link = response.css('img::attr(src)').extract_first() image_title = response.css('img::attr(alt)').extract_first() item = ImageItem() item['image_urls'] = [image_link] item['title'] = image_title yield item ``` 这样,当爬虫运行时,它将下载图像并将其信息插入到MySQL数据库

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值