Writing an image using NdefMessage

若如初见. 提交于 2019-12-06 08:03:22

Finally after searching for an application writting and reading Business card on NFC tag and finding nothing. I decided to create my own kind of business card and read it myself. here is the code i used to write the card using Ndef Message :

        Bitmap mBitmap = mPhoto;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
        byte[] byteArray = stream.toByteArray();
        NdefRecord picRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,  "image/jpeg".getBytes(), null, byteArray);
        String informations = "name: "+name + "\ntitle: " + title + "\naddress: "+ address + "\ncity: "+ city + "\nphone: "+ phone + "\nmail: "+mail + "\n";
        NdefRecord textRecord = createTextRecord(informations);
        NdefMessage message = new NdefMessage(new NdefRecord[]{picRecord, textRecord});

and here is the code for the reading part :

        NdefRecord picRecord = records[0];
        NdefRecord infoRecord = records[1];
        byte[] picload = picRecord.getPayload();
        byte[] infoload = infoRecord.getPayload();
        Bitmap photo = BitmapFactory.decodeByteArray(picload, 0, picload.length);
        String textEncoding = ((infoload[0] & 0200) == 0) ? "UTF-8" : "UTF-16";
        int languageCodeLength = infoload[0] & 0077;
        String text = null;
        try{
            String languageCode = new String(infoload, 1, languageCodeLength, "US-ASCII");
            text = new String(infoload, languageCodeLength + 1,infoload.length - languageCodeLength - 1, textEncoding);
        }catch(Exception e){
            Alert("String decoding", e.toString());
            return;
        }

The Jpeg encryption helps a lot to compress the image without loosing too much quality. The transfer on the tag take 2-3 seconds but the solution works well.

If your use case is storing business card on NFC tag, I would suggest that you do not store the image data but rather a link to the image. Otherwise you will have hard time storing the business card on a normal tags (usual size of the tags is 1K or 4K) and also time for transferring the data will be too long. According to the vCard specification you can do both: storing binary image data in base64 format and also url link(which I strongly recommend).

For more information about the format of the vCard look at here:

http://en.wikipedia.org/wiki/VCard

or in more details here:

http://tools.ietf.org/html/rfc2426#section-3.1.4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!