php - 在 mySQL blob 中存储图像

标签 php android mysql

我开发了一个 Android 应用程序,它将相机捕获的图像存储到 MySQL 数据库中。我试图将图像存储到 MySQL 数据库中的 Blob 字段中,但我无法将图像存储在数据库中,也无法在具有 ImageView 的 ListView 中从数据库中检索图像。我怎样才能做到这一点

因为我没有足够的资源将图像保存到文件中。这就是我采用这种方法的原因。

我使用下面的类将图像插入数据库。

 public class AddingImage extends Activity {
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_AddingImage);

    }

    public void Takeimage(View view)
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 0);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        Bitmap Imgaegot =(Bitmap) data.getExtras().get("data");
        imgview.setImageBitmap(Imgaegot);
    }

    // Onclick method called to add new asset to the Database
    public void SaveAssets(View v)
    {
            imgview.buildDrawingCache();
            Bitmap storeimage = imgview.getDrawingCache();

            String image_stores = ConverStringtobase64.encodeimageTobase64(storeimage);

            try {
                Storeencriptedvalue = normalTextEnc;
                inesrttoDatabase(image_stores);
            } catch (Exception e) {
                e.printStackTrace();
            }

            finish();
    }

    private void inesrttoDatabase(String Image)
    {
        class SendPostReqAsyncTask extends AsyncTask<String, Void,String>
        {
            @Override
            protected String doInBackground(String... params) {
                try
                {
                    posttext ();
                }catch (NullPointerException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);

                Toast.makeText(getApplicationContext(), "Data Inserted", Toast.LENGTH_LONG).show();
            }
        }

        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(Image);
    }

    private void posttext ()
    {
        try {
            Bitmap storeimage = imgview.getDrawingCache();
            String images = ConverStringtobase64.encodeimageTobase64(storeimage); ;

            // setting a namevalues pairs
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            //The string values are added to the namevaluespairs are added
            nameValuePairs.add(new BasicNameValuePair("Assetimage",images));

            // the Default client is set
            HttpClient httpClient = new DefaultHttpClient();
            /*A post request has been set  along with the url  to which the data will be posted to the
            data that is posted will then be saved on to the database using the PHP script that is been called by the link
            */
            HttpPost httpPost = new HttpPost("http://192.0.2.5/nfcams/insertingimage.php");

            // the values added to the namevalueParis is been passed using the httppost
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // The HTTP POST request is execute
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                String responseStr = EntityUtils.toString(entity).trim();
                Log.v("l", "Values have bee insertred: " + responseStr);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 }

我使用下面的 PHP 脚本将图像插入数据库。

    <?php
    include("connection.php");

    $Assetimage = $_POST['Assetimage'];

    $sqlinsert = "INSERT INTO `image` (`AImage`) VALUES ('{$Assetimage}')";

    $response = array();

    if(mysqli_query($con,$sqlinsert)) {
            // successfully inserted into database
            $response["success"] = 1;
            $response["message"] = "Product successfully created.";

            // echoing JSON response
            echo json_encode($response);
        } 
        else 
        {
            // failed to insert row
            $response["success"] = 0;
            $response["message"] = "Oops! An error occurred.";

            // echoing JSON response
            echo json_encode($response);
        } 

        mysqli_close($con);
    ?>

我还使用一个类将图像转换为 base64

public class ConverStringtobase64 {
    // The below method encodes the image to an String using base64 the bitmapimage is taken from the
    public static String encodeimageTobase64(Bitmap image)
    {
        //insta
        Bitmap imagebit = image;

        ByteArrayOutputStream img = new ByteArrayOutputStream();
        imagebit.compress(Bitmap.CompressFormat.PNG,100,img);

        byte [] bt = img.toByteArray();
        String imageEncode = Base64.encodeToString(bt,Base64.DEFAULT);
        return imageEncode;

    }


    public static Bitmap decodeImagetoBitmap(String imageDataString) {


        byte[] decodedByte = Base64.decode(imageDataString, 0);
        return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);

    }

}

为了从数据库中检索值,我使用了下面的 php 代码

<?php
include("connection.php");

$sql = "select * from `image`";

$res = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('id'=>$row['Assetid'],
'AImage'=>base64_encode($row['AImage'])
));
}

echo json_encode($result);

//mysql_close($con);

?>

最佳答案

将位图转换为字符串生成一个大字符串,确保数据库上的字段是字段类型文本并允许多个字符

关于php - 在 mySQL blob 中存储图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31575604/

相关文章:

mysql - 每个 x 字段只有 n 条记录

php - 如何创建一个每隔一小时自动运行一次并发送curl请求的脚本?

php - MySQL:更新没有保证唯一字段的行

android - 如果 Facebook App Invite 安装在 Android 上,它不会打开我的应用程序

android - 在处理 Android 草图时加载本地镜像

android - 快速点击 Android 的概览按钮两次时出现内部异常/崩溃

mysql - SQL嵌套查询问题

php - codeigniter 仅适用于 url 中的 index.php

php - Docker:Nginx 和 PHP 容器:没有这样的文件或目录

PHP PDO MS Access 如何读取 blob 图像?