Java从PostgreSQL读取字节数组并写入图像文件

时间:2019-03-06 09:48:19

标签: java postgresql image fileoutputstream bytea

我需要从PostgreSQL表中读取图像字节数组,其操作如下

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;


public class ButtonActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_button);
    }

    public void goToPayments(View view) {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

}

当我尝试将其写入图像文件时,它无法打开(不支持的文件类型)。以下是代码

byte[] fileBytes = resultsSet.getBytes(1);

1 个答案:

答案 0 :(得分:0)

尝试这种方法,对我有用:

      InputStream in = new ByteArrayInputStream(rs.getBytes(1));
      BufferedImage bImageFromConvert = ImageIO.read(in);
                    if(null == bImageFromConvert){
                        throw new Exception("Invalid image");
                    }
                    OutputStream out = new FileOutputStream("e:/images/"+"test".jpg");

        ImageIO.write(bImageFromConvert, "png", out);