如何从 mysql glob 类型中获取图像

Posted

技术标签:

【中文标题】如何从 mysql glob 类型中获取图像【英文标题】:How to get Image from mysql glob type 【发布时间】:2018-01-25 11:52:15 【问题描述】:

我在 mysql workbunch 中创建了一个数据库,并将图片作为 blob 类型存储在其中。 现在我想在我的应用中使用这张图片,

Class.forName("com.mysql.jdbc.Driver");
                try(Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sys", "root", "Elior204"))
                    Statement stmt = con.createStatement();
                    ResultSet rs = stmt.executeQuery("SELECT img FROM Sentences where id=1");
                       ImageView image = (ImageView) findViewById(R.id.imageView1);
                    Blob b =rs.getBlob(1);
                    int blobLength = (int) b.length();
                    byte[] blobAsBytes = b.getBytes(1, blobLength);
                    Bitmap btm =BitmapFactory.decodeByteArray(blobAsBytes,0,blobAsBytes.length);
                    image.setImageBitmap(btm );
                    con.close();

问题是,我该如何继续?

【问题讨论】:

你不能在android中直接访问mysql。你需要一个web服务来访问mysql数据。 当然可以,如果你include the right permissions נשמה של אבא דבר איתי כפרה jdbc:mysql://localhost 永远不会在 Android 设备中工作...除非你真的在那里运行 mysql 服务器 【参考方案1】:
java.sql.Blob blob = rs.getBlob(1);
byte[] imageContents = blob.getBytes(1, new Integer(blob.length()).intValue());

现在您可以随心所欲地操作它。

根据您的评论,您希望将其显示在您的应用程序中,为此,请将 ImageView 添加到您的布局并使用以下代码:

 image = (ImageView) findViewById(R.id.imageView1);

 button = (Button) findViewById(R.id.btnChangeImage);
 button.setOnClickListener(new OnClickListener() 

    @Override
    public void onClick(View arg0) 
          java.io.File tmpFileForImage = java.io.File.createTemporaryFile("image", ".png"); // or whatever your extension happens to be
          java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(new java.io.FileOutputStream(tmpFileForImage);
          bos.write(imageContents);
          bos.close();
          image.setImageResource(tmpFileForImage.getAbsolutePath());
    );

未经测试,但应该让您走上正轨。如果您需要进一步的帮助,请发表评论。

【讨论】:

我想在我的应用上显示图片,我该怎么做? 我编辑了我的问题,但它仍然无法正常工作,你知道为什么吗? 你得到了什么异常? 您错过了对 Asynctask 的需求以及移动设备不应该真正使用长期存在的 JDBC 对象这一事实

以上是关于如何从 mysql glob 类型中获取图像的主要内容,如果未能解决你的问题,请参考以下文章

如何获取文件夹中多个图像的轮廓

将图像从 MySQL 获取到 PyQt5 中的 tableWidget

mysql查询从3种类型中获取项目

如何使用mysql从图像表中获取总数?

如何从 PHAsset 获取原始图像和媒体类型?

如何从 NSArray 中获取图像 URL?