1

in my django project i want a user to upload a epub file (basically a rar file) . i want to extract the epub file to get cover of that epub and save that to imagefield or a file field

my idea is to extract a file using zipfile module as a binary data, but how to convert binary data to image field or binary field

@api_view(['POST'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def create_book(request, *args, **kwargs):
    serializer = Book_serialzier(
        data=request.data, context={"user": request.user})
    serializer.initial_data["title"] = serializer.initial_data.get(
        "book").name.split(".epub")[0]
    serializer.initial_data["user"] = request.user.id
    
    #here i started extracting
    with zipfile.ZipFile(serializer.initial_data.get("book"), 'r') as my_zip:
        if "cover.jpeg" in my_zip.namelist():
            serializer.initial_data["cover"] = my_zip.read("cover.jpeg")


    if(serializer.is_valid(raise_exception=True)):
        book = serializer.save()
    return Response(serializer.data)

emkay
  • 410
  • 1
  • 4
  • 12

1 Answers1

0

From your problem statement, I understand that you want to extract the cover image from the epub file and then save that to your field.

serializer.initial_data["cover"] = my_zip.read("cover.jpeg")

This line reads the byte-string and saves it into your "cover" field. You can easily convert that byte-string to the image by writing into a file in binary mode.

with open('cover_image.jpg','wb') as imageFile:
    imageFile.write(fileData) #fileData is what you will read from "cover" field

Best way to deal an image is to covert it in base64 format

You can do that easily like this

To covert back that base64 string into image you can do this