SlideShare a Scribd company logo
Deploying AI Apps using
TensorFlow Lite in Mobile
Devices
Colab - Keras - h5 - tflite - Android
#ISSLearningDay
Mr. Prasanna Veerapandi (Bala), NUS-ISS
2 Aug 2018
Agenda
• Intro to Deep Learning
• Build & Train CNN Models - colab
• Export Model to tflite
• Deploy tflite in android app
• Live Demo
• From Train Model ….. to Deploy in device
#ISSLearningDay
About me
• My name is Bala (Prasanna Veerapandi)
• I teach Python for Data , Ops & Things
#ISSLearningDay
Google : NUS ISS PYTHON
Intro to Deep Learning
SGD, NN, Back Prop, Arch, CNN, Keras, tflite
#ISSLearningDay
ML vs DL
Let’s see how with a simple
classifier
CAT vs DOG
Get Some Data- Binary Classifier (2 folders)
Choose a function y = f(x) *Simple
Choose a function y = f(x) *Intermediate
Choose a function y = f(x) *Deep
How it learns ?
TF Playground
SGD - Optimization
Once Trained : You get predictions
Build & Train CNN Models - colab
Data Preprocessing, Transform, Scale, Bachify, Hyper Param, Arch,
Training & Evaluate
#ISSLearningDay
Lets see some Keras Code
Import
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.callbacks import LearningRateScheduler
from tensorflow.keras.initializers import Constant
from tensorflow.keras.layers import Input, Conv2D, BatchNormalization
from tensorflow.keras.layers Activation, Dropout, Flatten, Dense
from tensorflow.keras.models import Model
from tensorflow.keras.utils import to_categorical
Load Data
NUM_CLASSES = 10
(x_train, y_train), (x_test, y_test) = mnist.load_data(path='mnist.npz')
x_train = x_train.reshape(*x_train.shape, 1)
x_test = x_test.reshape(*x_test.shape, 1)
x_train = x_train / 255.0
x_test = x_test / 255.0
y_train = to_categorical(y_train, NUM_CLASSES)
y_test = to_categorical(y_test, NUM_CLASSES)
print("x_train.shape = {}, y_train.shape = {}".format(x_train.shape,
y_train.shape))
Build a Model (Arch)
INPUT_SHAPE = (28, 28, 1)
NUM_CLASSES = 10
model = keras.Sequential()
model.add( Input(shape=INPUT_SHAPE, name='input') )
model.add( Conv2D(24, kernel_size=(6, 6), strides=1) )
model.add( MaxPooling2D( pool_size=(2, 2) ) )
model.add( BatchNormalization(scale=False, beta_initializer=Constant(0.01)) )
model.add( Activation('relu') )
model.add( tf.keras.layers.Flatten() )
model.add( Dense(200) )
model.add( BatchNormalization(scale=False, beta_initializer=Constant(0.01)) )
model.add( Activation('relu'))
model.add( Dropout(rate=0.25))
model.add( Dense(NUM_CLASSES, activation='softmax', name='output') )
Model Summary
Remember the model Arch... *Intermediate
Build a Model (Arch) - Add more layers...
INPUT_SHAPE = (28, 28, 1)
NUM_CLASSES = 10
model = keras.Sequential()
model.add( Input(shape=INPUT_SHAPE, name='input') )
model.add( Conv2D(24, kernel_size=(6, 6), strides=1) )
model.add( BatchNormalization(scale=False, beta_initializer=Constant(0.01)) )
model.add( Activation('relu') )
model.add( Conv2D(48, kernel_size=(5, 5), strides=2) )
model.add( MaxPooling2D( pool_size=(2, 2) ) )
model.add( BatchNormalization(scale=False, beta_initializer=Constant(0.01)) )
model.add( Activation('relu') )
model.add( Conv2D(64, kernel_size=(4, 4), strides=2) )
model.add( MaxPooling2D( pool_size=(2, 2) ) )
model.add( BatchNormalization(scale=False, beta_initializer=Constant(0.01)) )
model.add( Activation('relu') )
model.add( tf.keras.layers.Flatten() )
model.add( Dense(200) )
model.add( BatchNormalization(scale=False, beta_initializer=Constant(0.01)) )
model.add( Activation('relu'))
model.add( Dropout(rate=0.25))
Model Summary
Compile the model
# Get an Optimizer
adam = keras.optimizers.Adam(lr=0.001)
model.compile(loss='categorical_crossentropy',
optimizer=adam,
metrics=['accuracy'])
Lets Train the model
history = model.fit(x_train,
y_train, batch_size=128,
epochs=2, verbose=1,
validation_data=(x_test, y_test))
Export Model to tflite
Keras, .h5, tflite converter
#ISSLearningDay
NUS-ISS Learning Day 2019-Deploying AI apps using tensor flow lite in mobile devices
Export h5 to tflite
model.save('mnist.h5')
converter = tf.lite.TFLiteConverter.from_keras_model_file('mnist.h5')
tflite_model = converter.convert()
with open('mnist.tflite', 'wb') as f:
f.write(tflite_model)
Demo Time
http://bit.ly/train-mnist
Deploy tflite in android app
org.tensorflow:tensorflow-lite:1.13.1 , Interpreter
classifier , labels.txt,
Interpreter.run( data , result )
#ISSLearningDay
Android APP
build.gradle
aaptOptions {
noCompress "tflite"
noCompress "lite"
}
dependencies {
implementation 'org.tensorflow:tensorflow-lite:1.13.1'
}
Copy model into assets folder
mnist.tflite
labels.txt || labels.json
File Size in 1..5 Mbs
Model file size
quick-draw-tflite = 442 Kb
File Size in 1..5 Mbs
Configure input Shapes
public class MnistDigitClassifier {
private static final String MODEL_NAME = "mnist.tflite";
private static final int BATCH_SIZE = 1;
public static final int IMG_HEIGHT = 28;
public static final int IMG_WIDTH = 28;
private static final int NUM_CHANNEL = 1;
private static final int NUM_CLASSES = 10;
private final Interpreter.Options options = new Interpreter.Options();
private final Interpreter mInterpreter;
private final ByteBuffer mImageData;
private final int[] mImagePixels = new int[IMG_HEIGHT * IMG_WIDTH];
private final float[][] mResult = new float[1][NUM_CLASSES];
}
new Interpreter()
public class MnistDigitClassifier {
public MnistDigitClassifier(Activity activity) throws IOException {
mInterpreter = new Interpreter(loadModelFile(activity), options);
mImageData = ByteBuffer.allocateDirect(
4 * BATCH_SIZE * IMG_HEIGHT * IMG_WIDTH * NUM_CHANNEL);
mImageData.order(ByteOrder.nativeOrder());
}
}
Predict : Classify
public class MnistDigitClassifier {
public Result classify(Bitmap bitmap) {
convertBitmapToByteBuffer(bitmap);
mInterpreter.run(mImageData, mResult);
Result r = new Result(mResult[0], timeCost);
r.setLabel(String.valueOf(r.getNumber()));
return r;
}
Demo Time
http://bit.ly/quickdraw-tflite
Appendix
// How to get the bitmap
Bitmap image = mFpvPaint.exportToBitmap(
QuickDrawClassifier.IMG_WIDTH,
QuickDrawClassifier.IMG_HEIGHT);
private MappedByteBuffer loadModelFile(Activity activity) throws IOException {
AssetFileDescriptor fileDescriptor = activity.getAssets().openFd(MODEL_NAME);
FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
FileChannel fileChannel = inputStream.getChannel();
long startOffset = fileDescriptor.getStartOffset();
long declaredLength = fileDescriptor.getDeclaredLength();
return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}
https://github.com/balaprasanna/quick-
draw-keras-tflite-android
Code
Q/A
Thank You!
bala@nus.edu.sg
#ISSLearningDay

More Related Content

PDF
NUS-ISS Learning Day 2019-Pandas in the cloud
KEY
Python 的文件系統
DOC
Devry gsp 215 week 6 i lab virtual memory new
PDF
TensorFlow Dev Summit 2018 Extended: TensorFlow Eager Execution
PDF
Network Analysis with networkX : Real-World Example-1
PPT
PDF
Kmeans plusplus
PPT
Heap sort
NUS-ISS Learning Day 2019-Pandas in the cloud
Python 的文件系統
Devry gsp 215 week 6 i lab virtual memory new
TensorFlow Dev Summit 2018 Extended: TensorFlow Eager Execution
Network Analysis with networkX : Real-World Example-1
Kmeans plusplus
Heap sort

What's hot (20)

PDF
Network Analysis with networkX : Real-World Example-2
PDF
Heaps
PPTX
Presentation on Heap Sort
PDF
[4DEV][Łódź] Ivan Vaskevych - InfluxDB and Grafana fighting together with IoT...
PPT
Data Structure and Algorithms Heaps and Trees
PPTX
Binary Heap Tree, Data Structure
PDF
PPTX
Python library
PPTX
Scala Style by Adform Research (Saulius Valatka)
PDF
Metrics 2.0 @ Monitorama PDX 2014
PPTX
Heap sort
PPT
Heapsort
PPTX
Stack Data structure
PDF
Parquet Vectorization in Hive
PDF
MBrace: Large-scale cloud computation with F# (CUFP 2014)
PDF
Python for R Users
PDF
MBrace: Cloud Computing with F#
PPTX
Heap Sort in Design and Analysis of algorithms
Network Analysis with networkX : Real-World Example-2
Heaps
Presentation on Heap Sort
[4DEV][Łódź] Ivan Vaskevych - InfluxDB and Grafana fighting together with IoT...
Data Structure and Algorithms Heaps and Trees
Binary Heap Tree, Data Structure
Python library
Scala Style by Adform Research (Saulius Valatka)
Metrics 2.0 @ Monitorama PDX 2014
Heap sort
Heapsort
Stack Data structure
Parquet Vectorization in Hive
MBrace: Large-scale cloud computation with F# (CUFP 2014)
Python for R Users
MBrace: Cloud Computing with F#
Heap Sort in Design and Analysis of algorithms
Ad

Similar to NUS-ISS Learning Day 2019-Deploying AI apps using tensor flow lite in mobile devices (20)

PDF
ML in Android
PDF
iOS와 케라스의 만남
PDF
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...
PDF
Power ai tensorflowworkloadtutorial-20171117
PDF
Keras and TensorFlow
PDF
Inference accelerators
PDF
maXbox starter65 machinelearning3
PDF
Icpp power ai-workshop 2018
PDF
Siddha Ganju, NVIDIA. Deep Learning for Mobile
PDF
Siddha Ganju. Deep learning on mobile
PDF
OpenPOWER Workshop in Silicon Valley
PDF
Anirudh Koul. 30 Golden Rules of Deep Learning Performance
PDF
On-device ML with TFLite
PDF
TensorFlow and Keras: An Overview
PDF
프알못의 Keras 사용기
PPTX
From Tensorflow Graph to Tensorflow Eager
PDF
Neural Networks from Scratch - TensorFlow 101
PDF
Persian MNIST in 5 Minutes
PPTX
TensorFlow in Practice
PDF
A Tour of Tensorflow's APIs
ML in Android
iOS와 케라스의 만남
XebiCon'17 : Faites chauffer les neurones de votre Smartphone avec du Deep Le...
Power ai tensorflowworkloadtutorial-20171117
Keras and TensorFlow
Inference accelerators
maXbox starter65 machinelearning3
Icpp power ai-workshop 2018
Siddha Ganju, NVIDIA. Deep Learning for Mobile
Siddha Ganju. Deep learning on mobile
OpenPOWER Workshop in Silicon Valley
Anirudh Koul. 30 Golden Rules of Deep Learning Performance
On-device ML with TFLite
TensorFlow and Keras: An Overview
프알못의 Keras 사용기
From Tensorflow Graph to Tensorflow Eager
Neural Networks from Scratch - TensorFlow 101
Persian MNIST in 5 Minutes
TensorFlow in Practice
A Tour of Tensorflow's APIs
Ad

More from NUS-ISS (20)

PDF
Designing Impactful Services and User Experience - Lim Wee Khee
PDF
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...
PDF
The Importance of Cybersecurity for Digital Transformation
PDF
Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu...
PDF
Understanding GenAI/LLM and What is Google Offering - Felix Goh
PDF
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze
PDF
Emerging & Future Technology - How to Prepare for the Next 10 Years of Radica...
PDF
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
PDF
Supply Chain Security for Containerised Workloads - Lee Chuk Munn
PDF
Future of Learning - Yap Aye Wee.pdf
PDF
Future of Learning - Khoong Chan Meng
PPTX
Site Reliability Engineer (SRE), We Keep The Lights On 24/7
PDF
Product Management in The Trenches for a Cloud Service
PDF
Overview of Data and Analytics Essentials and Foundations
PDF
Predictive Analytics
PDF
Feature Engineering for IoT
PDF
Master of Technology in Software Engineering
PDF
Master of Technology in Enterprise Business Analytics
PDF
Diagnosing Complex Problems Using System Archetypes
PPTX
Satisfying the ‘-ilities’ of an Enterprise Cloud Service
Designing Impactful Services and User Experience - Lim Wee Khee
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...
The Importance of Cybersecurity for Digital Transformation
Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu...
Understanding GenAI/LLM and What is Google Offering - Felix Goh
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze
Emerging & Future Technology - How to Prepare for the Next 10 Years of Radica...
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
Supply Chain Security for Containerised Workloads - Lee Chuk Munn
Future of Learning - Yap Aye Wee.pdf
Future of Learning - Khoong Chan Meng
Site Reliability Engineer (SRE), We Keep The Lights On 24/7
Product Management in The Trenches for a Cloud Service
Overview of Data and Analytics Essentials and Foundations
Predictive Analytics
Feature Engineering for IoT
Master of Technology in Software Engineering
Master of Technology in Enterprise Business Analytics
Diagnosing Complex Problems Using System Archetypes
Satisfying the ‘-ilities’ of an Enterprise Cloud Service

Recently uploaded (20)

PDF
cuic standard and advanced reporting.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
DOCX
The AUB Centre for AI in Media Proposal.docx
cuic standard and advanced reporting.pdf
NewMind AI Weekly Chronicles - August'25 Week I
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Advanced methodologies resolving dimensionality complications for autism neur...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Review of recent advances in non-invasive hemoglobin estimation
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Network Security Unit 5.pdf for BCA BBA.
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Understanding_Digital_Forensics_Presentation.pptx
Encapsulation_ Review paper, used for researhc scholars
“AI and Expert System Decision Support & Business Intelligence Systems”
Mobile App Security Testing_ A Comprehensive Guide.pdf
Machine learning based COVID-19 study performance prediction
Dropbox Q2 2025 Financial Results & Investor Presentation
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
The AUB Centre for AI in Media Proposal.docx

NUS-ISS Learning Day 2019-Deploying AI apps using tensor flow lite in mobile devices

  • 1. Deploying AI Apps using TensorFlow Lite in Mobile Devices Colab - Keras - h5 - tflite - Android #ISSLearningDay Mr. Prasanna Veerapandi (Bala), NUS-ISS 2 Aug 2018
  • 2. Agenda • Intro to Deep Learning • Build & Train CNN Models - colab • Export Model to tflite • Deploy tflite in android app • Live Demo • From Train Model ….. to Deploy in device #ISSLearningDay
  • 3. About me • My name is Bala (Prasanna Veerapandi) • I teach Python for Data , Ops & Things #ISSLearningDay Google : NUS ISS PYTHON
  • 4. Intro to Deep Learning SGD, NN, Back Prop, Arch, CNN, Keras, tflite #ISSLearningDay
  • 6. Let’s see how with a simple classifier CAT vs DOG
  • 7. Get Some Data- Binary Classifier (2 folders)
  • 8. Choose a function y = f(x) *Simple
  • 9. Choose a function y = f(x) *Intermediate
  • 10. Choose a function y = f(x) *Deep
  • 11. How it learns ? TF Playground
  • 13. Once Trained : You get predictions
  • 14. Build & Train CNN Models - colab Data Preprocessing, Transform, Scale, Bachify, Hyper Param, Arch, Training & Evaluate #ISSLearningDay
  • 15. Lets see some Keras Code
  • 16. Import import tensorflow as tf from tensorflow.keras.datasets import mnist from tensorflow.keras.callbacks import LearningRateScheduler from tensorflow.keras.initializers import Constant from tensorflow.keras.layers import Input, Conv2D, BatchNormalization from tensorflow.keras.layers Activation, Dropout, Flatten, Dense from tensorflow.keras.models import Model from tensorflow.keras.utils import to_categorical
  • 17. Load Data NUM_CLASSES = 10 (x_train, y_train), (x_test, y_test) = mnist.load_data(path='mnist.npz') x_train = x_train.reshape(*x_train.shape, 1) x_test = x_test.reshape(*x_test.shape, 1) x_train = x_train / 255.0 x_test = x_test / 255.0 y_train = to_categorical(y_train, NUM_CLASSES) y_test = to_categorical(y_test, NUM_CLASSES) print("x_train.shape = {}, y_train.shape = {}".format(x_train.shape, y_train.shape))
  • 18. Build a Model (Arch) INPUT_SHAPE = (28, 28, 1) NUM_CLASSES = 10 model = keras.Sequential() model.add( Input(shape=INPUT_SHAPE, name='input') ) model.add( Conv2D(24, kernel_size=(6, 6), strides=1) ) model.add( MaxPooling2D( pool_size=(2, 2) ) ) model.add( BatchNormalization(scale=False, beta_initializer=Constant(0.01)) ) model.add( Activation('relu') ) model.add( tf.keras.layers.Flatten() ) model.add( Dense(200) ) model.add( BatchNormalization(scale=False, beta_initializer=Constant(0.01)) ) model.add( Activation('relu')) model.add( Dropout(rate=0.25)) model.add( Dense(NUM_CLASSES, activation='softmax', name='output') )
  • 20. Remember the model Arch... *Intermediate
  • 21. Build a Model (Arch) - Add more layers... INPUT_SHAPE = (28, 28, 1) NUM_CLASSES = 10 model = keras.Sequential() model.add( Input(shape=INPUT_SHAPE, name='input') ) model.add( Conv2D(24, kernel_size=(6, 6), strides=1) ) model.add( BatchNormalization(scale=False, beta_initializer=Constant(0.01)) ) model.add( Activation('relu') ) model.add( Conv2D(48, kernel_size=(5, 5), strides=2) ) model.add( MaxPooling2D( pool_size=(2, 2) ) ) model.add( BatchNormalization(scale=False, beta_initializer=Constant(0.01)) ) model.add( Activation('relu') ) model.add( Conv2D(64, kernel_size=(4, 4), strides=2) ) model.add( MaxPooling2D( pool_size=(2, 2) ) ) model.add( BatchNormalization(scale=False, beta_initializer=Constant(0.01)) ) model.add( Activation('relu') ) model.add( tf.keras.layers.Flatten() ) model.add( Dense(200) ) model.add( BatchNormalization(scale=False, beta_initializer=Constant(0.01)) ) model.add( Activation('relu')) model.add( Dropout(rate=0.25))
  • 23. Compile the model # Get an Optimizer adam = keras.optimizers.Adam(lr=0.001) model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])
  • 24. Lets Train the model history = model.fit(x_train, y_train, batch_size=128, epochs=2, verbose=1, validation_data=(x_test, y_test))
  • 25. Export Model to tflite Keras, .h5, tflite converter #ISSLearningDay
  • 27. Export h5 to tflite model.save('mnist.h5') converter = tf.lite.TFLiteConverter.from_keras_model_file('mnist.h5') tflite_model = converter.convert() with open('mnist.tflite', 'wb') as f: f.write(tflite_model)
  • 29. Deploy tflite in android app org.tensorflow:tensorflow-lite:1.13.1 , Interpreter classifier , labels.txt, Interpreter.run( data , result ) #ISSLearningDay
  • 31. build.gradle aaptOptions { noCompress "tflite" noCompress "lite" } dependencies { implementation 'org.tensorflow:tensorflow-lite:1.13.1' }
  • 32. Copy model into assets folder mnist.tflite labels.txt || labels.json File Size in 1..5 Mbs
  • 33. Model file size quick-draw-tflite = 442 Kb File Size in 1..5 Mbs
  • 34. Configure input Shapes public class MnistDigitClassifier { private static final String MODEL_NAME = "mnist.tflite"; private static final int BATCH_SIZE = 1; public static final int IMG_HEIGHT = 28; public static final int IMG_WIDTH = 28; private static final int NUM_CHANNEL = 1; private static final int NUM_CLASSES = 10; private final Interpreter.Options options = new Interpreter.Options(); private final Interpreter mInterpreter; private final ByteBuffer mImageData; private final int[] mImagePixels = new int[IMG_HEIGHT * IMG_WIDTH]; private final float[][] mResult = new float[1][NUM_CLASSES]; }
  • 35. new Interpreter() public class MnistDigitClassifier { public MnistDigitClassifier(Activity activity) throws IOException { mInterpreter = new Interpreter(loadModelFile(activity), options); mImageData = ByteBuffer.allocateDirect( 4 * BATCH_SIZE * IMG_HEIGHT * IMG_WIDTH * NUM_CHANNEL); mImageData.order(ByteOrder.nativeOrder()); } }
  • 36. Predict : Classify public class MnistDigitClassifier { public Result classify(Bitmap bitmap) { convertBitmapToByteBuffer(bitmap); mInterpreter.run(mImageData, mResult); Result r = new Result(mResult[0], timeCost); r.setLabel(String.valueOf(r.getNumber())); return r; }
  • 38. Appendix // How to get the bitmap Bitmap image = mFpvPaint.exportToBitmap( QuickDrawClassifier.IMG_WIDTH, QuickDrawClassifier.IMG_HEIGHT); private MappedByteBuffer loadModelFile(Activity activity) throws IOException { AssetFileDescriptor fileDescriptor = activity.getAssets().openFd(MODEL_NAME); FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor()); FileChannel fileChannel = inputStream.getChannel(); long startOffset = fileDescriptor.getStartOffset(); long declaredLength = fileDescriptor.getDeclaredLength(); return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength); }