在mySQL blob中存储图像

时间:2015-07-22 23:15:12

标签: php android mysql

我开发了一个Android应用程序,可将摄像头捕获的图像存储到MySQL数据库中。我试图将图像存储到MySQL数据库中的Blob字段中,但我无法将图像存储在数据库中,也无法从具有ImageView的列表视图中的数据库中检索图像。我该怎么做

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

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

 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);

?>

1 个答案:

答案 0 :(得分:2)

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