简体   繁体   中英

Storing an Image in mySQL blob

I have developed an Android application that stores camera captured images to a MySQL database. I am trying to store images into a Blob field in MySQL database but I am not able to store the image in the database and also not able to retrieve the image from the database in my list view that has the ImageView. How can i do this

Since I did not have enough resource to save the images to a file. That why I have adopted this method.

I have used the below class to insert the image in the database.

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

I have used the below PHP script to insert the image in the database.

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

I am also using a class to convert the image to 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);

    }

}

In order to retrieve the values from the database I have used the below php code

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

?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM