【问题标题】:How to get Image from mysql glob type如何从 mysql glob 类型中获取图像
【发布时间】: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 服务器

标签: java android mysql jdbc


【解决方案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 对象这一事实
猜你喜欢
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
  • 2013-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多